static async Task GetAudio(string location, string fileName) { var yt = new YoutubeDL(); yt.Options.FilesystemOptions.Output = $@"e:\test\{fileName}"; yt.Options.PostProcessingOptions.ExtractAudio = true; yt.Options.PostProcessingOptions.AudioFormat = Enums.AudioFormat.mp3; yt.VideoUrl = location; yt.Options.GeneralOptions.Update = true; yt.YoutubeDlPath = $@"e:\test\youtube-dl.exe"; yt.StandardOutputEvent += (sender, output) => Console.WriteLine(output); yt.StandardErrorEvent += (sender, errorOutput) => Console.WriteLine(errorOutput); // string commandToRun = await yt.PrepareDownloadAsync(); // Alternatively string commandToRun = yt.PrepareDownload(); // Just let it run await yt.DownloadAsync(); // Wait for it // yt.Download(); }
public static async Task <bool> ValidCookie(IServerApplicationPaths appPaths, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var ytd = new YoutubeDL(); var task = ytd.DownloadAsync("https://www.youtube.com/playlist?list=WL"); List <string> ytdl_errs = new(); ytd.StandardErrorEvent += (sender, error) => ytdl_errs.Add(error); ytd.Options.VideoSelectionOptions.PlaylistItems = "0"; ytd.Options.VerbositySimulationOptions.SkipDownload = true; var cookie_file = Path.Join(appPaths.PluginsPath, "YoutubeMetadata", "cookies.txt"); if (File.Exists(cookie_file)) { ytd.Options.FilesystemOptions.Cookies = cookie_file; } await task; foreach (string err in ytdl_errs) { var match = Regex.Match(err, @".*The playlist does not exist\..*"); if (match.Success) { return(false); } } return(true); }
public async Task YTDL(CommandContext ctx, string link) { if (link.Contains("youtu") || link.Contains("nico")) { var msg = await ctx.RespondAsync("Download started!"); System.Random random = new System.Random(); const string pool = "abcdefghijklmnopqrstuvwxyz0123456789"; var chars = Enumerable.Range(0, 20) .Select(x => pool[random.Next(0, pool.Length)]); string finalString = new string(chars.ToArray()); var youtubeDl = new YoutubeDL(); if (link.Contains("youtu")) { youtubeDl.Options.FilesystemOptions.Output = $"/var/www/vhosts/srgg.de/why-is-this-a-me.me/ytdl/{finalString}.mp4"; youtubeDl.Options.VideoSelectionOptions.NoPlaylist = true; } if (link.Contains("nico")) { youtubeDl.Options.FilesystemOptions.Output = $"/var/www/vhosts/srgg.de/why-is-this-a-me.me/nnddl/{finalString}.mp4"; youtubeDl.Options.FilesystemOptions.NoCacheDir = true; } youtubeDl.Options.PostProcessingOptions.ExtractAudio = true; youtubeDl.Options.VideoFormatOptions.Format = NYoutubeDL.Helpers.Enums.VideoFormat.best; youtubeDl.Options.PostProcessingOptions.ExtractAudio = true; youtubeDl.Options.PostProcessingOptions.AudioFormat = NYoutubeDL.Helpers.Enums.AudioFormat.mp3; youtubeDl.Options.PostProcessingOptions.AudioQuality = "320k"; youtubeDl.Options.PostProcessingOptions.AddMetadata = true; youtubeDl.Options.PostProcessingOptions.EmbedThumbnail = true; youtubeDl.Options.GeneralOptions.Update = true; youtubeDl.VideoUrl = link; youtubeDl.YoutubeDlPath = "youtube-dl"; youtubeDl.StandardErrorEvent += (sender, errorOutput) => ctx.RespondAsync($"{errorOutput} (If its 403 blame NNDs Servers, hella slow sometimes and thus cancel the download uwu)"); await youtubeDl.DownloadAsync(); if (File.Exists($"/var/www/vhosts/srgg.de/why-is-this-a-me.me/ytdl/{finalString}.mp3")) { await msg.ModifyAsync("https://why-is-this-a-me.me/ytdl/" + finalString + ".mp3 \n" + "**This file will be deleted in about 30min!**"); await Task.Delay((60000 * 30)); File.Delete($"/var/www/vhosts/srgg.de/why-is-this-a-me.me/ytdl/{finalString}.mp3"); } else if (File.Exists($"/var/www/vhosts/srgg.de/why-is-this-a-me.me/nnddl/{finalString}.mp3")) { await msg.ModifyAsync("https://why-is-this-a-me.me/nnddl/" + finalString + ".mp3 \n" + "**This file will be deleted in about 30min!**"); await Task.Delay((60000 * 30)); File.Delete($"/var/www/vhosts/srgg.de/why-is-this-a-me.me/nnddl/{finalString}.mp3"); } } else { await ctx.RespondAsync("no YouTube or NND link detected, please try again"); } }
/// https://github.com/BrianAllred/NYoutubeDL/commit/2bd39515eebb8c5fb866687781165804e3b0579f public async Task YouTubeDownloader(string _link, string _extension, string _path) { try { var youtubeDl = new YoutubeDL(); #region File Name string name = Random(100000, 999999).ToString(); while (File.Exists(_path + @"\" + name + _extension)) { name = Random(100000, 999999).ToString(); } #endregion File Name youtubeDl.Options.FilesystemOptions.Output = _path + @"\" + name + _extension; if (_extension == ".mp3") { youtubeDl.Options.PostProcessingOptions.ExtractAudio = true; } youtubeDl.VideoUrl = _link; youtubeDl.YoutubeDlPath = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Milkenm\Bronze Player", "Path", null).ToString() + "youtube-dl.exe"; await youtubeDl.PrepareDownloadAsync(); await youtubeDl.DownloadAsync(); } #region DE3UG catch (Exception exception) { tools.Exception(exception); } #endregion DE3UG }
public static async Task YTDLMetadata(string id, IServerApplicationPaths appPaths, CancellationToken cancellationToken) { //var foo = await ValidCookie(appPaths, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var ytd = new YoutubeDL(); ytd.Options.FilesystemOptions.WriteInfoJson = true; ytd.Options.VerbositySimulationOptions.SkipDownload = true; var cookie_file = Path.Join(appPaths.PluginsPath, "YoutubeMetadata", "cookies.txt"); if (File.Exists(cookie_file)) { ytd.Options.FilesystemOptions.Cookies = cookie_file; } var dlstring = "https://www.youtube.com/watch?v=" + id; var dataPath = Path.Combine(appPaths.CachePath, "youtubemetadata", id, "ytvideo"); ytd.Options.FilesystemOptions.Output = dataPath; List <string> ytdl_errs = new(); ytd.StandardErrorEvent += (sender, error) => ytdl_errs.Add(error); var task = ytd.DownloadAsync(dlstring); await task; }
public async Task DownloadYoutubeVideo(string videoUrl, string localPath, Action <string, string, string> progressCallback) { var youtubeDl = new YoutubeDL(); youtubeDl.VideoUrl = videoUrl; youtubeDl.Options.FilesystemOptions.Output = localPath; youtubeDl.Options.PostProcessingOptions.ExtractAudio = false; youtubeDl.Options.DownloadOptions.FragmentRetries = -1; youtubeDl.Options.DownloadOptions.Retries = -1; youtubeDl.Options.VideoFormatOptions.Format = Enums.VideoFormat.best; youtubeDl.Options.PostProcessingOptions.AudioFormat = Enums.AudioFormat.best; youtubeDl.Options.PostProcessingOptions.AudioQuality = "0"; youtubeDl.StandardOutputEvent += (sender, s) => { var pattern = @"(?<progress>[^ ]{1,10}%).*?at.*?(?<rate>\d[^ ]{1,10}MiB\/s).*?(?<ETA>ETA [^ ]*)"; var match = Regex.Match(s, pattern); if (match.Success) { progressCallback(match.Groups["progress"].Value, match.Groups["rate"].Value, match.Groups["ETA"].Value); } }; await youtubeDl.DownloadAsync(); }
public static async Task <string> SearchChannel(string query, IServerApplicationPaths appPaths, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var ytd = new YoutubeDL(); var url = String.Format(Constants.SearchQuery, System.Web.HttpUtility.UrlEncode(query)); ytd.Options.VerbositySimulationOptions.Simulate = true; ytd.Options.GeneralOptions.FlatPlaylist = true; ytd.Options.VideoSelectionOptions.PlaylistItems = "1"; ytd.Options.VerbositySimulationOptions.PrintField = "url"; List <string> ytdl_errs = new(); List <string> ytdl_out = new(); ytd.StandardErrorEvent += (sender, error) => ytdl_errs.Add(error); ytd.StandardOutputEvent += (sender, output) => ytdl_out.Add(output); var cookie_file = Path.Join(appPaths.PluginsPath, "YoutubeMetadata", "cookies.txt"); if (File.Exists(cookie_file)) { ytd.Options.FilesystemOptions.Cookies = cookie_file; } var task = ytd.DownloadAsync(url); await task; Uri uri = new Uri(ytdl_out[0]); return(uri.Segments[uri.Segments.Length - 1]); }
private async void MusicSearchButton_Click(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(textBox1.Text)) { MessageBox.Show("Поисковая строка пустая!"); } else { try { if (announcer == true) { playVoiceLine(3); } await Task.Run(async() => yt.Start(textBox1.Text)); if (String.IsNullOrWhiteSpace(yt.videoKey)) { MessageBox.Show("Nothing found!"); } else { axWindowsMediaPlayer1.Visible = false; axWindowsMediaPlayer1.close(); textBox1.Text = yt.videoTitile; path = yt.videoTitile + "-" + yt.videoKey + ".mp4"; { path = path.Replace("&", "&"); path = path.Replace("|", "_"); path = path.Replace("*", "_"); path = path.Replace("/", "_"); path = path.Replace(@"\", "_"); path = path.Replace(":", "_"); path = path.Replace("?", "_"); path = path.Replace(""", "'"); } // Fixing problems with path, cause video can contains symbols like /, or ?, which not exits in file names in Windows OC var youtubeDl = new YoutubeDL(); youtubeDl.YoutubeDlPath = @"..\..\Videos\youtube-dl.exe"; youtubeDl.Options.PostProcessingOptions.ExtractAudio = true; youtubeDl.Options.VideoFormatOptions.Format = NYoutubeDL.Helpers.Enums.VideoFormat.worst; MessageBox.Show(path); await youtubeDl.DownloadAsync($"https://www.youtube.com/watch?v={yt.videoKey}"); new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.DeleteOnClose); axWindowsMediaPlayer1.Visible = true; axWindowsMediaPlayer1.URL = path; axWindowsMediaPlayer1.Ctlcontrols.play(); } } catch { MessageBox.Show("Ошибки случаются"); } } }
public async void ProcessQueue() { processingQueue = true; Parallel.ForEach(Queue, async item => //foreach (var item in Queue) { if (item.Status == "Queued") { var fileName = item.Title + ".mp4"; var location = item.Url; var items = new List <string>(); var yt = new YoutubeDL(); yt.Options.FilesystemOptions.Output = $@"e:\test\{fileName}"; yt.Options.PostProcessingOptions.ExtractAudio = true; yt.Options.PostProcessingOptions.AudioFormat = Enums.AudioFormat.mp3; yt.VideoUrl = location; yt.Options.GeneralOptions.Update = true; yt.YoutubeDlPath = $@"e:\test\youtube-dl.exe"; yt.StandardOutputEvent += (sender, output) => { Console.WriteLine(output); ConsoleText = output; items.Add(output); var pct = item.Percent; if (output.Contains("[download]") && output.Contains('%')) { var s = output.IndexOf('%'); var num = output.Substring(10, s - 10); var numc = num.Trim(); pct = Decimal.Parse(numc); item.Percent = pct; item.Status = "Downloading"; } if (item.Percent == 100) { item.Status = "Processing"; } if (output.StartsWith("Deleting")) { item.Status = "Done"; } }; yt.StandardErrorEvent += (sender, errorOutput) => Console.WriteLine(errorOutput); string commandToRun = yt.PrepareDownload(); await yt.DownloadAsync(); } }); processingQueue = false; }
public async Task <string> Download(string url, string name) { Console.WriteLine("Queueing download..."); return(await _queueService.Enqueue(async() => { Console.WriteLine("Starting download..."); await _youtubeDl.DownloadAsync(url); return await _streamableService.Upload(name); })); }
/// <summary> /// Gets the download links and creates the global VideoQualityFormats object /// </summary> /// <param name="url">VOD url</param> /// <returns>Task that contains the VideoQualityObject for the URL</returns> private async Task <VideoQualityFormat> getVideoFormats(string url) { VideoQualityFormat data = null; var updateGUIThread = new Progress <Boolean>((value) => { if (value) { //loading image while video quality links loads selectedVODPictureBox.Image = Properties.Resources.loadingIcon; } else { //replace loading image with stream thumbnail try { selectedVODPictureBox.Load(_selectedVOD.thumbnail_url.Replace("%{width}", "300").Replace("%{height}", "300")); } catch (Exception e) { selectedVODPictureBox.Load(_selectedVOD.thumbnail_url.Replace("%{width}", "300").Replace("%{height}", "300")); Console.WriteLine(e.Message); } } }); var updateMainForm = updateGUIThread as IProgress <Boolean>; string videoQualityRawJSON = ""; var youtubeDL = new YoutubeDL() { VideoUrl = url, YoutubeDlPath = Properties.Settings.Default.YoutubeDLLocation }; youtubeDL.Options.VerbositySimulationOptions.DumpJson = true; youtubeDL.StandardOutputEvent += (sender, output) => { Console.WriteLine(output); videoQualityRawJSON = output; }; youtubeDL.StandardErrorEvent += (sender, errorOutput) => Console.WriteLine(errorOutput); updateMainForm.Report(true); //downloads the json for video quality await youtubeDL.DownloadAsync(); data = JsonConvert.DeserializeObject <VideoQualityFormat>(videoQualityRawJSON); updateMainForm.Report(false); return(data); }
public void YoutubeBuffer(string url) { try { youtubeDl.DownloadAsync(url); Trace.WriteLine(String.Format("Buffering video {0}", url)); } catch (Exception ex) { Trace.WriteLine(String.Format("Error at {0}", ex)); } }
public static async Task <string> DownloadMP4Async(string url) { var youtubeDL = new YoutubeDL(); string fileName = DateTime.Now.ToString("yyyyMMdd_HHmmssffff"); youtubeDL.Options.FilesystemOptions.Output = fileName + @".%(ext)s"; youtubeDL.Options.VideoFormatOptions.Format = NYoutubeDL.Helpers.Enums.VideoFormat.best; youtubeDL.Options.PostProcessingOptions.RecodeFormat = NYoutubeDL.Helpers.Enums.VideoFormat.mp4; youtubeDL.VideoUrl = url; await youtubeDL.DownloadAsync(); return(fileName + ".mp4"); }
public static async Task <string> DownloadMP3Async(string url) { var youtubeDL = new YoutubeDL(); string fileName = DateTime.Now.ToString("yyyyMMdd_HHmmssffff"); youtubeDL.Options.FilesystemOptions.Output = fileName + @".%(ext)s"; youtubeDL.VideoUrl = url; youtubeDL.Options.PostProcessingOptions.ExtractAudio = true; youtubeDL.Options.PostProcessingOptions.AudioFormat = NYoutubeDL.Helpers.Enums.AudioFormat.mp3; youtubeDL.Options.PostProcessingOptions.AudioQuality = "0"; await youtubeDL.DownloadAsync(); return(fileName + ".mp3"); }
public static async Task <MemoryStream> DownloadPlaylistMP3Async(string url) { var youtubeDL = new YoutubeDL(); string directoryName = DateTime.Now.ToString("yyyyMMdd_HHmmssffff"); System.IO.Directory.CreateDirectory(directoryName); youtubeDL.Options.FilesystemOptions.Output = Path.Combine(directoryName, @"%(playlist_index)s-%(title)s.%(ext)s"); youtubeDL.VideoUrl = url; youtubeDL.Options.PostProcessingOptions.ExtractAudio = true; youtubeDL.Options.PostProcessingOptions.AudioFormat = NYoutubeDL.Helpers.Enums.AudioFormat.mp3; youtubeDL.Options.PostProcessingOptions.AudioQuality = "0"; await youtubeDL.DownloadAsync(); var files = CreateZipFile(directoryName, "mp3"); Directory.Delete(directoryName, true); return(files); }
private void GetUrl(string url) { BlockBegin(); var ytdl = new YoutubeDL(); ytdl.Options.VerbositySimulationOptions.DumpSingleJson = true; ytdl.VideoUrl = url; // Since we're calling from another thread, we need some fuckery ytdl.StandardOutputEvent += (sender, output) => Invoke( new GotUrlSafeDelegate(GotUrl), new object[] { JObject.Parse(output) } ); ytdl.StandardOutputEvent += (sender, output) => Console.WriteLine(output); ytdl.StandardErrorEvent += (sender, output) => Console.WriteLine(output); ytdl.DownloadAsync(); }
public async Task <bool> DownloadVideo(string url, string fileName) { try { var youtubeDl = new YoutubeDL(); youtubeDl.Options.FilesystemOptions.Output = GetDownloadDirctory() + $@"\{fileName}.mp4"; youtubeDl.Options.VideoFormatOptions.Format = Enums.VideoFormat.mp4; youtubeDl.VideoUrl = url; youtubeDl.StandardOutputEvent += (sender, output) => Console.WriteLine(output); youtubeDl.StandardErrorEvent += (sender, errorOutput) => Console.WriteLine(errorOutput); await youtubeDl.DownloadAsync(); return(true); } catch { return(false); } }
public static async Task <MemoryStream> GetBilibili(string s, DiscordMessage msg) { try { await msg.ModifyAsync("Downloading video(this may take up to 5 min)"); var youtubeDl = new YoutubeDL(@"youtube-dl"); youtubeDl.Options.FilesystemOptions.Output = $@"{s}.mp4"; youtubeDl.Options.PostProcessingOptions.ExtractAudio = true; youtubeDl.Options.PostProcessingOptions.FfmpegLocation = @"ffmpeg"; youtubeDl.Options.PostProcessingOptions.AudioFormat = NYoutubeDL.Helpers.Enums.AudioFormat.mp3; youtubeDl.Options.PostProcessingOptions.AddMetadata = true; youtubeDl.Options.PostProcessingOptions.KeepVideo = false; youtubeDl.StandardOutputEvent += (e, f) => { Console.WriteLine(f); }; youtubeDl.StandardErrorEvent += (e, f) => { Console.WriteLine(f); }; youtubeDl.VideoUrl = "https://www.bilibili.com/video/" + s; await youtubeDl.DownloadAsync(); var ms = new MemoryStream(); if (File.Exists($@"{s}.mp3")) { var song = File.Open($@"{s}.mp3", FileMode.Open); await song.CopyToAsync(ms); ms.Position = 0; song.Close(); File.Delete($@"{s}.mp3"); } return(ms); } catch (Exception ex) { Console.WriteLine(ex); return(null); } }
public async Task DownloadClips(Discord discord, Database database, List <ClipInfo> clips) { YoutubeDL twitchDownload = new YoutubeDL(); string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/clips"; await database.OpenDBConnection(); foreach (ClipInfo clip in clips.ToList()) { if (!await database.CheckIfClipAlreadyExists(clip.id)) { string tempPath = path + $"/{clip.id}.mp4"; try { twitchDownload.Options.FilesystemOptions.Output = tempPath; twitchDownload.VideoUrl = clip.url; await twitchDownload.DownloadAsync(); await discord.UploadClipToDiscord(tempPath, clip); await database.ClipToDatabase(clip); } catch (Exception ex) { List <string> msg = new List <string>(); msg.Add(ex.Message); msg.Add(ex.StackTrace); Program.Logging.Log(msg); } finally { if (File.Exists(tempPath)) { File.Delete(tempPath); } } } } await database.CloseDBConnection(); Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss") + " finished"); }
private void downloadButton_Click(object sender, EventArgs e) { Form1 fm1 = new Form1(); fm1.loadVoiceLines(); fm1.playVoiceLine(2); try { if (String.IsNullOrWhiteSpace(downloadTextBox.Text) != true && downloadTextBox.Text.IndexOf("youtube.com/watch?") != -1) { MessageBox.Show("Происходит загрузка"); if (isCustomPathTriggered == false) { youtubeDl.Options.FilesystemOptions.Output = @"..\..\Videos\%(title)s.%(ext)s"; } else { youtubeDl.Options.FilesystemOptions.Output = customPath; } youtubeDl.DownloadAsync(downloadTextBox.Text); if (isCustomPathTriggered == false) { MessageBox.Show($"Загружено в 'Videos folder', возле программы"); } else { MessageBox.Show($"Успешно выгружено в: {customPath}"); } } else { MessageBox.Show("Все ошибаются, но ты - особенно часто. Проверь ссылку"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static async Task GetChannelInfo(string id, string name, IServerApplicationPaths appPaths, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var ytd = new YoutubeDL(); ytd.Options.VideoSelectionOptions.PlaylistItems = "0"; ytd.Options.FilesystemOptions.WriteInfoJson = true; var dataPath = Path.Combine(appPaths.CachePath, "youtubemetadata", name, "ytvideo"); ytd.Options.FilesystemOptions.Output = dataPath; var cookie_file = Path.Join(appPaths.PluginsPath, "YoutubeMetadata", "cookies.txt"); if (File.Exists(cookie_file)) { ytd.Options.FilesystemOptions.Cookies = cookie_file; } List <string> ytdl_errs = new(); ytd.StandardErrorEvent += (sender, error) => ytdl_errs.Add(error); var task = ytd.DownloadAsync(String.Format(Constants.ChannelUrl, id)); await task; }
private async Task <DownloadResponse> DownloadSong(SongRequest request) { await _batcher.WaitAsync(); try { var youtubeDl = new YoutubeDL(); var standardOutBuilder = new StringBuilder(); var standardErrorBuilder = new StringBuilder(); youtubeDl.StandardOutputEvent += (s, output) => standardOutBuilder.Append(output); youtubeDl.StandardErrorEvent += (s, error) => standardErrorBuilder.Append(error); var artistPath = Path.Combine(request.Artist[0].ToString(), request.Artist); var artistAlbumPath = Path.Combine(artistPath, request.Album); var artistAlbumFilePath = Path.Combine(artistAlbumPath, $"{request.Title}.m4a"); var fullFilePath = Path.Combine(MusicArtistsDirectory, artistAlbumFilePath); youtubeDl.Options.FilesystemOptions.Output = fullFilePath; youtubeDl.Options.VideoFormatOptions.FormatAdvanced = "bestaudio[ext=m4a]"; var info = await youtubeDl.GetDownloadInfoAsync(); await youtubeDl.DownloadAsync(request.Url); return(new DownloadResponse(request.Url, info.Title, standardOutBuilder.ToString(), standardErrorBuilder.ToString())); } catch (Exception) { throw; } finally { _batcher.Release(); } }
private void UiDownloadButton_Click(object sender, EventArgs e) { string url = uiUrlTextBox.Text; if (String.IsNullOrWhiteSpace(url)) { MessageBox.Show("Please enter a video URL", "No URL Entered", MessageBoxButtons.OK, MessageBoxIcon.Error); uiUrlTextBox.Focus(); return; } uiDownloadButton.Enabled = false; string videoLocation = Path.Combine(Constants.VideoCacheLocation, "temp_video_download.mp4"); this.InvokeIfRequired(() => uiStatusLabel.Text = "Starting download... Please wait as this can take a few seconds to start."); try { youtubeDl = new YoutubeDL { YoutubeDlPath = "youtube-dl.exe", VideoUrl = url, }; youtubeDl.Options.FilesystemOptions.Output = videoLocation; youtubeDl.Options.GeneralOptions.IgnoreErrors = true; youtubeDl.PrepareDownload(); youtubeDl.Info.PropertyChanged += (o, args) => { DownloadInfo info = (DownloadInfo)o; string status = info.Status; this.InvokeIfRequired(() => uiDownloadProgressBar.Value = info.VideoProgress); this.InvokeIfRequired(() => uiStatusLabel.Text = $"Status: {status} Video size: {info.VideoSize} Download speed: {info.DownloadRate} ETA: {info.Eta}"); if (status == "Error") { this.InvokeIfRequired(() => uiStatusLabel.Text = "Error downloading video."); this.InvokeIfRequired(() => uiDownloadButton.Enabled = true); youtubeDl.KillProcess(); } if (status == "Done" || info.VideoProgress == 100) { this.InvokeIfRequired(() => uiDownloadButton.Enabled = true); this.InvokeIfRequired(() => uiStatusLabel.Text = "Status: Download complete. Processing video."); if (!hasFired) //this can fire multiple times, so stop it from happening with flag. Need to reset after download completed! { hasFired = true; youtubeDl.KillProcess(); VideoDownloadComplete?.Invoke(this, EventArgs.Empty); this.InvokeIfRequired(() => Close()); } } }; youtubeDl.DownloadAsync(); } catch (ArgumentOutOfRangeException) { MessageBox.Show("An error has occured attempting to download this video.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private async void button1_Click(object sender, EventArgs e) { txtTerminal.AppendText("Starting a video download run..."); mainProgressBar.Visible = true; txtVideoUrl.Enabled = false; button1.Enabled = false; btnChange.Enabled = false; menuStrip1.Enabled = false; var youtubeDl = new YoutubeDL(); // Optional, required if binary is not in $PATH youtubeDl.YoutubeDlPath = "lib\\youtube-dl.exe"; youtubeDl.VideoUrl = txtVideoUrl.Text; youtubeDl.Options.PostProcessingOptions.FfmpegLocation = "lib\\ffmpeg.exe"; youtubeDl.Options.PostProcessingOptions.PreferFfmpeg = true; var tmpDateTime = DateTime.Now.ToString("ddMMyyyy hhmmss"); var tmpFn = CleanFileName(tmpDateTime); if (chkAudioOnly.Checked) { tmpFn = $"{txtSaveFolder.Text}\\{tmpFn}.partial.%(ext)s"; youtubeDl.Options.FilesystemOptions.Output = tmpFn; youtubeDl.Options.PostProcessingOptions.AudioFormat = NYoutubeDL.Helpers.Enums.AudioFormat.mp3; youtubeDl.Options.PostProcessingOptions.KeepVideo = false; youtubeDl.Options.PostProcessingOptions.ExtractAudio = true; } else { tmpFn = $"{txtSaveFolder.Text}\\{tmpFn}.partial.mp4"; youtubeDl.Options.FilesystemOptions.Output = tmpFn; youtubeDl.Options.VideoFormatOptions.Format = NYoutubeDL.Helpers.Enums.VideoFormat.mp4; youtubeDl.Options.PostProcessingOptions.KeepVideo = true; } string commandToRun = await youtubeDl.PrepareDownloadAsync(); youtubeDl.StandardOutputEvent += (sdr, output) => { Console.WriteLine(output); this.txtTerminal.Invoke((Action) delegate { this.txtTerminal.AppendText(Environment.NewLine + output); }); }; youtubeDl.StandardErrorEvent += (sdr, errorOutput) => Console.WriteLine(errorOutput); // Prepare the download (in case you need to validate the command before starting the download) //string commandToRun = await youtubeDl.PrepareDownloadAsync(); youtubeDl.Info.PropertyChanged += delegate { this.mainProgressBar.Invoke((Action) delegate { this.mainProgressBar.Value = youtubeDl.Info.VideoProgress; }); //mainProgressBar.Update(); //var val = youtubeDl.Info.VideoProgress; }; //var vidTitle = youtubeDl.Info.Title; // Just let it run await youtubeDl.DownloadAsync(); txtVideoUrl.Enabled = true; button1.Enabled = true; mainProgressBar.Visible = false; btnChange.Enabled = true; menuStrip1.Enabled = true; if (!chkAudioOnly.Checked) { if (youtubeDl.Info != null && youtubeDl.Info.Title != null) { var newFilename = tmpFn.Replace(".partial", "").Replace(tmpDateTime, CleanFileName(youtubeDl.Info.Title)); File.Move(tmpFn, newFilename); txtTerminal.AppendText(Environment.NewLine + $"Saved as {newFilename}"); } else { var newFilename = tmpFn.Replace(".partial", ""); File.Move(tmpFn, newFilename); txtTerminal.AppendText(Environment.NewLine + $"Saved as {newFilename}"); } } else { //Download YouTube image url if (txtVideoUrl.Text.Contains("youtube")) { var youtubeMatch = new Regex(@"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)") .Match(txtVideoUrl.Text); var ytId = youtubeMatch.Success ? youtubeMatch.Groups[1].Value : string.Empty; if (!string.IsNullOrWhiteSpace(ytId)) { var imageBytes = await GetImageAsByteArray($"/vi/{ytId}/0.jpg", "https://img.youtube.com"); var fnToFind = tmpFn.Replace(@".partial.%(ext)s", ".partial.mp3"); ////Add an image to the audio file. TagLib.Id3v2.Tag.DefaultVersion = 3; TagLib.Id3v2.Tag.ForceDefaultVersion = true; var fileToEdit = TagLib.File.Create(fnToFind); fileToEdit.Tag.Title = "Untitled"; if (youtubeDl.Info != null && youtubeDl.Info.Title != null) { fileToEdit.Tag.Title = youtubeDl.Info.Title; } fileToEdit.Tag.Performers = new[] { "YouTube Downloader" }; fileToEdit.Tag.AlbumArtists = new[] { "YouTube Downloader" }; fileToEdit.Tag.Album = "YouTube"; fileToEdit.Tag.Year = (uint)DateTime.Now.Year; fileToEdit.Tag.Genres = new[] { "Pop" }; fileToEdit.Tag.Comment = " "; fileToEdit.Tag.Track = 1; var pic = new TagLib.Picture { Type = TagLib.PictureType.FrontCover, Description = "Cover", MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg, Data = imageBytes }; fileToEdit.Tag.Pictures = new TagLib.IPicture[] { pic }; var dt = fileToEdit.Tag.Pictures[0].Data.Data; fileToEdit.Save(); } } //Rename the audio file. if (youtubeDl.Info != null && youtubeDl.Info.Title != null) { var fnToFind = tmpFn.Replace(@".partial.%(ext)s", ".partial.mp3"); var newFilename = fnToFind.Replace(".partial", "").Replace(tmpDateTime, CleanFileName(youtubeDl.Info.Title)); File.Move(fnToFind, newFilename); txtTerminal.AppendText(Environment.NewLine + $"Audio saved as {newFilename}"); } else { var fnToFind = tmpFn.Replace(@".partial.%(ext)s", ".partial.mp3"); var newFilename = fnToFind.Replace(".partial", ""); File.Move(fnToFind, newFilename); txtTerminal.AppendText(Environment.NewLine + $"Audio saved as {newFilename}"); } } }
private async void bGo_Click(object sender, RoutedEventArgs e) { textStatus.Text = "Preparing"; gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render); var downloader = new YoutubeDL(); string fileName = ""; downloader.VideoUrl = tbLink.Text; downloader.Options.FilesystemOptions.NoMtime = true; //downloader.Options.VideoFormatOptions.Format = NYoutubeDL.Helpers.Enums.VideoFormat.best; downloader.Options.VerbositySimulationOptions.CallHome = false; downloader.Options.GeneralOptions.Update = true; //downloader.Options.VideoFormatOptions.FormatAdvanced = string videoTitleNoFilter = downloader.GetDownloadInfo().Title; string videoTitle = Regex.Replace(videoTitleNoFilter, @"[^a-z,0-9, ,-]", "", RegexOptions.IgnoreCase); Random random = new Random(); int randomInt = random.Next(1, 1000); downloader.Options.FilesystemOptions.Output = filePath + $"\\video{randomInt}"; if (cboxCut.IsChecked == false && cboxConvert.IsChecked == false) { downloader.Options.FilesystemOptions.Output = filePath + $"\\{videoTitle}"; } downloader.YoutubeDlPath = runningPath + "\\youtube-dl.exe"; if (rbBest.IsChecked == true) { downloader.Options.VideoFormatOptions.FormatAdvanced = "best"; } else { downloader.Options.VideoFormatOptions.FormatAdvanced = "worst"; } if (cboxResolution.Text != "Auto") { downloader.Options.VideoFormatOptions.FormatAdvanced += $"[height <=? {Int32.Parse(cboxResolution.Text.TrimEnd('p'))}]"; } textStatus.Text = "Downloading"; downloader.DownloadAsync(); while (downloader.IsDownloading) { pbProgress.Value = downloader.Info.VideoProgress; textETA.Text = "ETA: " + downloader.Info.Eta; textSpeed.Text = "Speed: " + downloader.Info.DownloadRate; gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render); } pbProgress.Value = 0; textETA.Text = "ETA: ?"; textSpeed.Text = "Speed: ?"; gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render); foreach (string file in Directory.GetFiles(filePath)) { if (Path.GetFileName(file).StartsWith($"video{randomInt}")) { fileName = file; } } if (cboxCut.IsChecked == true || cboxConvert.IsChecked == true) { pbProgress.IsIndeterminate = true; textStatus.Text = "Getting FFmpeg"; gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render); if (!File.Exists(runningPath + "\\ffmpeg.exe")) { await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full, runningPath); } textStatus.Text = "Processing"; gridMain.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Render); var conversions = FFmpeg.Conversions.New(); if (cboxCut.IsChecked == true) { conversions.AddParameter($"-ss {TimeSpan.FromSeconds(Int32.Parse(tbFrom.Text))}"); } conversions.AddParameter($"-i \"{fileName}\""); if (cboxConvert.IsChecked == true) { conversions.SetOutput($"{filePath}\\{videoTitle}{cbConvertType.Text}"); } else { conversions.SetOutput($"{filePath}\\{videoTitle}{Path.GetExtension(fileName)}"); } if (cboxCut.IsChecked == true) { conversions.AddParameter($"-to {TimeSpan.FromSeconds(Int32.Parse(tbTo.Text) - Int32.Parse(tbFrom.Text))}"); } /* * if (cboxConvert.IsChecked == true && cboxCut.IsChecked == false) * await conversions.AddParameter($"-i \"{fileName}\" \"{filePath}\\{videoTitle}{cbConvertType.Text}\"").Start(); * if (cboxConvert.IsChecked == true && cboxCut.IsChecked == true) * await conversions.AddParameter($"-ss {TimeSpan.FromSeconds(Int32.Parse(tbFrom.Text))} -i \"{fileName}\" -to {TimeSpan.FromSeconds(Int32.Parse(tbTo.Text) - Int32.Parse(tbFrom.Text))} -c copy \"{filePath + $"\\{videoTitle}{cbConvertType.Text}"}\"").Start(); * if (cboxConvert.IsChecked == false && cboxCut.IsChecked == true) * await conversions.AddParameter($"-ss {TimeSpan.FromSeconds(Int32.Parse(tbFrom.Text))} -i \"{fileName}\" -to {TimeSpan.FromSeconds(Int32.Parse(tbTo.Text) - Int32.Parse(tbFrom.Text))} -c copy \"{filePath + $"\\{videoTitle}{Path.GetExtension(fileName)}"}\"").Start();*/ await conversions.Start(); File.Delete(fileName); pbProgress.IsIndeterminate = false; } textStatus.Text = "Idle"; }
public async Task UploadClip([Remainder] string urlArray) { List <string> links = new List <string>(); links = urlArray.Split('\n', ' ').ToList(); //ulong.Parse(configuration.GetSettings("Discord_Server")), ulong.Parse(configuration.GetSettings("Discord_Channel") SocketGuild server = Context.Client.GetGuild(ulong.Parse(Program.configuration.GetSettings("Discord_Server"))); // Get Channel to send clips to SocketTextChannel channel = server.GetChannel(ulong.Parse(Program.configuration.GetSettings("Discord_Channel"))) as SocketTextChannel; Database database = new Database(Program.configuration.GetConnectionString("Clips")); string clipId = ""; // [obsolete FS] IDisposable typingDM = Context.Channel.EnterTypingState(); await Context.Channel.SendMessageAsync("Now starting upload of " + links.Count + " clip/s"); try { foreach (string url in links) { if (url.StartsWith("clips.twitch.tv")) { clipId = url.Split("/")[1]; } else if (url.StartsWith("http")) { clipId = url.Split("//")[1].Split("/")[1]; } else { clipId = url; } if (clipId != "") { string TwitchApiUrl = "https://api.twitch.tv/helix/clips?id=" + clipId; string responseBody = await Twitch.twitch.GetAsync(TwitchApiUrl).Result.Content.ReadAsStringAsync(); TwitchClass streamTwitch = JsonSerializer.Deserialize <TwitchClass>(responseBody); if (streamTwitch.data.Count != 0) { ClipInfo clip = streamTwitch.data[0]; if (clip.broadcaster_id == Program.configuration.GetSettings("Broadcaster_ID")) { DateTime currentTime = DateTime.UtcNow; DateTime oneDayAgo = currentTime.AddDays(-1); if (clip.created_at < oneDayAgo) { YoutubeDL twitchDownload = new YoutubeDL(); string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/clips"; await database.OpenDBConnection(); if (ignoreDB || (await database.CheckIfClipAlreadyExists(clip.id)) == false) { string tempPath = path + $"/{clip.id}.mp4"; try { twitchDownload.Options.FilesystemOptions.Output = tempPath; twitchDownload.VideoUrl = clip.url; // [obsolete FS] IDisposable typing = channel.EnterTypingState(); await twitchDownload.DownloadAsync(); await channel.SendFileAsync(tempPath, "", false, CreateEmbed(clip)); // [obsolete FS] typing.Dispose(); await database.ClipToDatabase(clip); await Context.Channel.SendMessageAsync("Clip " + clip.id + " uploaded successfully"); Program.Logging.Log("User " + Context.User.Username + "(id: " + Context.User.Id + ")" + " uploaded a Clip (ID: " + clip.id + ")"); } catch (Exception ex) { Program.Logging.Log(ex.Message + "\n" + ex.StackTrace); } finally { if (File.Exists(tempPath)) { File.Delete(tempPath); } } } else { await Context.Channel.SendMessageAsync("The Clip \"" + clip.id + "\" already exists"); } await database.CloseDBConnection(); } else { DateTime creation = clip.created_at.AddDays(1); await Context.Channel.SendMessageAsync("Clip (id: " + clip.id + ") has to be older than 24 hours, you can request the clip at " + creation.ToString("dd.MM.yyyy hh:mm:ss tt") + " UTC"); } } else { await Context.Channel.SendMessageAsync("The clip (id: " + clip.id + ") has to be from Sean_VR"); } } else { await Context.Channel.SendMessageAsync("Clip (id: " + clipId + ") not found"); } } } } catch (Exception ex) { Program.Logging.Log(ex.Message + "\n" + ex.StackTrace); } // [obsolete FS] typingDM.Dispose(); await Context.Channel.SendMessageAsync("Finished"); }