Ejemplo n.º 1
0
        static async Task Main(string[] args)
        {
            var url = args[0];
            var dl  = new YoutubeDL();

            dl.Options.FilesystemOptions.Output           = ".";
            dl.Options.PostProcessingOptions.ExtractAudio = true;
            dl.VideoUrl = url;

            dl.StandardErrorEvent += (s, o) => {
                Console.WriteLine("?? {0}", o);
            };

            dl.StandardOutputEvent += (s, o) => {
                Console.WriteLine(":: {0}", o);
            };

            // dl.Info.PropertyChanged += (s, o) => {
            //     Console.WriteLine("~ {0}", o);
            // };

            var rs = await dl.PrepareDownloadAsync();

            Console.WriteLine("> {0}", rs);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Synchronously download a video/playlist
        /// </summary>
        /// <param name="ydl">
        ///     The client
        /// </param>
        /// <param name="cancellationToken">
        ///     The cancellation token
        /// </param>
        internal static void Download(this YoutubeDL ydl, CancellationToken cancellationToken)
        {
            cancellationToken.Register(() =>
            {
                Cancel(ydl);
            });

            if (!ydl.isGettingInfo)
            {
                ydl.IsDownloading = true;
            }

            if (ydl.processStartInfo == null)
            {
                ydl.isGettingInfo = true;
                PreparationService.PrepareDownload(ydl, cancellationToken);

                if (ydl.processStartInfo == null)
                {
                    throw new NullReferenceException();
                }

                ydl.isGettingInfo = false;
            }

            SetupDownload(ydl, cancellationToken);

            ydl.process?.WaitForExit();

            if (!ydl.isGettingInfo)
            {
                ydl.IsDownloading    = false;
                ydl.processStartInfo = null;
            }
        }
Ejemplo n.º 3
0
    // Token: 0x060059CA RID: 22986 RVA: 0x001F290C File Offset: 0x001F0D0C
    private IEnumerator FindURIs(string url, Action onDone = null)
    {
        if (this.foundURIs.ContainsKey(url))
        {
            this.foundURIs.Remove(url);
        }
        yield return(YoutubeDL.FindBestVideoURL(url, false, delegate(string found)
        {
            if (!this.foundURIs.ContainsKey(url))
            {
                this.foundURIs.Add(url, new List <string>
                {
                    found
                });
            }
            else
            {
                this.foundURIs[url].Add(found);
            }
        }, delegate(string err)
        {
            Debug.LogError(err);
        }));

        if (!this.foundURIs.ContainsKey(url))
        {
            this.foundURIs.Add(url, new List <string>());
        }
        if (onDone != null)
        {
            onDone();
        }
        yield break;
    }
Ejemplo n.º 4
0
 /// <summary>
 /// Performs the download of the specified video with the given YoutubeDL instance and a prior overwrite check.
 /// </summary>
 public async Task <RunResult <string> > RunDownload(YoutubeDL ydl, VideoEntry video,
                                                     CancellationToken ct, IProgress <DownloadProgress> progress, OptionSet overrideOptions = null)
 {
     if ((Settings.Default.OverwriteMode != OverwriteMode.Overwrite) && allowsOverwriteCheck)
     {
         bool   restricted = ydl.RestrictFilenames;
         string ext        = GetExt();
         string fileName   = Utils.Sanitize(video.Title, restricted);
         string path       = Path.Combine(ydl.OutputFolder, $"{fileName}.{ext}");
         if (File.Exists(path))
         {
             if (Settings.Default.OverwriteMode == OverwriteMode.None)
             {
                 // Don't redownload if file exists.
                 progress?.Report(new DownloadProgress(DownloadState.Success, data: path));
                 return(new RunResult <string>(true, new string[0], path));
             }
             else
             {
                 // Set download path to a new location to prevent overwriting existing file.
                 string downloadPath = getNotExistingFilePath(ydl.OutputFolder, fileName, ext);
                 if (overrideOptions == null)
                 {
                     overrideOptions = new OptionSet();
                 }
                 overrideOptions.Output = downloadPath;
             }
         }
     }
     return(await RunRealDownload(ydl, video.Url, ct, progress, overrideOptions));
 }
        /// <summary>
        /// Verifies if the url of a job is valid and adding the result to it.
        /// </summary>
        /// <param name="job">The job object that should be verified.</param>
        private static async Task VerifyUrl(DownloadJob job)
        {
            var dl     = new YoutubeDL();
            var result = await dl.RunVideoDataFetch(job.Url);

            if (result.Data == null)
            {
                if (result.ErrorOutput.Contains("Forbidden"))
                {
                    job.VerificationResult = VerificationResult.DrmProtected;
                    return;
                }

                if (result.ErrorOutput.Contains("Unsupported Url"))
                {
                    job.VerificationResult = VerificationResult.NoVideoFound;
                    return;
                }

                job.VerificationResult = VerificationResult.GenericError;
                return;
            }

            if (result.Data.Entries != null)
            {
                job.VerificationResult = VerificationResult.IsPlaylist;
                return;
            }

            job.VideoData          = result.Data;
            job.VerificationResult = VerificationResult.Valid;
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Performs the download of the specified playlist with the given YoutubeDL instance and a prior overwrite check.
 /// </summary>
 public async Task <RunResult <string[]> > RunDownload(YoutubeDL ydl, PlaylistEntry playlist,
                                                       CancellationToken ct, IProgress <DownloadProgress> progress, OptionSet overrideOptions = null)
 {
     if (!ydl.OverwriteFiles && allowsOverwriteCheck)
     {
         bool   restricted = ydl.RestrictFilenames;
         string ext        = GetExt();
         // Check if some videos have already been downloaded.
         var indices = new List <int>();
         int index   = 1;
         foreach (var video in playlist.Metadata.Entries)
         {
             string path = Path.Combine(ydl.OutputFolder, $"{Utils.Sanitize(video.Title, restricted)}.{ext}");
             System.Diagnostics.Debug.WriteLine(path);
             if (!File.Exists(path))
             {
                 indices.Add(index);
             }
             else
             {
                 progress?.Report(new DownloadProgress(DownloadState.Success, data: path));
             }
             index++;
         }
         return(await RunRealPlaylistDownload(ydl, playlist.Url,
                                              indices.ToArray(), ct, progress, overrideOptions));
     }
     else
     {
         return(await RunRealPlaylistDownload(ydl, playlist.Url, null, ct, progress, overrideOptions));
     }
 }
Ejemplo n.º 7
0
        //public async Task<IActionResult> Download(string url = null, FormatoDescarga format = FormatoDescarga.mp3, TimeSpan? TiempoInicio = null, TimeSpan? TiempoFin = null)
        public async Task <IActionResult> Download(string url = null, FormatoDescarga format = FormatoDescarga.mp3)
        {
            var youtubeDL  = new YoutubeDL();
            var metaClient = new YoutubeClient();

            string mediaUrl      = WebUtility.UrlDecode(url);
            var    mediaMetadata = await metaClient.GetVideoAsync(YoutubeClient.ParseVideoId(mediaUrl));

            Task <string> fileTask = null;

            switch (format)
            {
            case FormatoDescarga.mp3:
                fileTask = Utils.DownloadMP3Async(mediaUrl);
                break;

            case FormatoDescarga.mp4:
                fileTask = Utils.DownloadMP4Async(mediaUrl);
                break;
            }
            MemoryStream media = new MemoryStream(System.IO.File.ReadAllBytes(fileTask.Result));

            media.Seek(0, SeekOrigin.Begin);
            System.IO.File.Delete(fileTask.Result);
            return(new FileStreamResult(media, "application/octet-stream")
            {
                FileDownloadName = (mediaMetadata.Title + Path.GetExtension(fileTask.Result))
            });
        }
Ejemplo n.º 8
0
 public static void Initialize(TestContext context)
 {
     ydl = new YoutubeDL();
     ydl.YoutubeDLPath = "Lib\\youtube-dl.exe";
     ydl.FFmpegPath    = "Lib\\ffmpeg.exe";
     downloadedFiles   = new List <string>();
 }
Ejemplo n.º 9
0
        /// <summary>
        ///     synchronously prepare a youtube-dl command
        /// </summary>
        /// <param name="ydl">
        ///     The client.
        /// </param>
        /// <param name="cancellationToken">
        ///     The cancellation token
        /// </param>
        /// <returns>
        ///     The youtube-dl command that will be executed
        /// </returns>
        internal static string PrepareDownload(this YoutubeDL ydl, CancellationToken cancellationToken)
        {
            if (!ydl.Info.set)
            {
                Delegate[] originalDelegates = null;
                if (ydl.Info.propertyChangedEvent != null)
                {
                    originalDelegates = ydl.Info.propertyChangedEvent.GetInvocationList();
                }

                ydl.Info = InfoService.GetDownloadInfo(ydl, cancellationToken) ?? new DownloadInfo();

                if (originalDelegates != null)
                {
                    foreach (Delegate del in originalDelegates)
                    {
                        ydl.Info.PropertyChanged += (PropertyChangedEventHandler)del;
                    }
                }

                ydl.Info.set = true;
            }

            SetupPrepare(ydl);

            return(ydl.RunCommand);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Asynchronously retrieve video / playlist information
        /// </summary>
        /// <param name="ydl">
        /// The client
        /// </param>
        /// <param name="url">
        /// URL of video / playlist
        /// </param>
        /// <returns>
        /// An object containing the download information
        /// </returns>
        internal static async Task <DownloadInfo> GetDownloadInfoAsync(this YoutubeDL ydl, string url)
        {
            ydl.VideoUrl = url;
            await GetDownloadInfoAsync(ydl);

            return(ydl.Info);
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     Setup a youtube-dl command using the given options
        /// </summary>
        /// <param name="ydl">
        ///     Client with configured options
        /// </param>
        internal static void SetupPrepare(YoutubeDL ydl)
        {
            string arguments = ydl.Options.ToCliParameters() + " " + ydl.VideoUrl;

            ydl.processStartInfo = new ProcessStartInfo
            {
                FileName               = YoutubeDL.YoutubeDlPath,
                Arguments              = arguments,
                CreateNoWindow         = true,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };

            if (string.IsNullOrWhiteSpace(ydl.processStartInfo.FileName))
            {
                throw new FileNotFoundException("youtube-dl not found on path!");
            }

            if (!File.Exists(ydl.processStartInfo.FileName))
            {
                throw new FileNotFoundException($"{ydl.processStartInfo.FileName} not found!");
            }

            ydl.RunCommand = ydl.processStartInfo.FileName + " " + ydl.processStartInfo.Arguments;
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Setup a youtube-dl command using the given options
        /// </summary>
        /// <param name="ydl">
        ///     Client with configured options
        /// </param>
        internal static void SetupPrepare(YoutubeDL ydl)
        {
            string urls      = string.IsNullOrWhiteSpace(ydl.VideoUrl) ? string.Empty : string.Join(" ", ydl.VideoUrl.Split(null).Select(url => $"\"{url}\""));
            string arguments = ydl.Options.ToCliParameters() + " " + urls;

            ydl.processStartInfo = new ProcessStartInfo
            {
                FileName               = ydl.YoutubeDlPath,
                Arguments              = arguments,
                CreateNoWindow         = true,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };

            if (!string.IsNullOrWhiteSpace(ydl.PythonPath))
            {
                ydl.processStartInfo.Arguments = ydl.YoutubeDlPath + " " + ydl.processStartInfo.Arguments;
                ydl.processStartInfo.FileName  = ydl.PythonPath;
            }

            if (string.IsNullOrWhiteSpace(ydl.processStartInfo.FileName))
            {
                throw new FileNotFoundException("youtube-dl not found on path!");
            }

            if (!File.Exists(ydl.processStartInfo.FileName))
            {
                throw new FileNotFoundException($"{ydl.processStartInfo.FileName} not found!");
            }

            ydl.RunCommand = ydl.processStartInfo.FileName + " " + ydl.processStartInfo.Arguments;
        }
Ejemplo n.º 13
0
        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");
            }
        }
Ejemplo n.º 14
0
        public async Task DownloadLatest()
        {
            // This will download the new version and add it to "Versions" map
            log.LogInformation("Checking for new youtube-dl version...");
            await ytdlManager.DownloadLatestVersion();

            // Critical section - replace ytdl when nobody uses it
            var latest = ytdlManager.Versions.Keys.Max();

            if (CurrentVersion != latest)
            {
                log.LogInformation("New version found {0}!", CurrentVersion);
                using (var @lock = await ytdlLock.WriterLockAsync())
                {
                    // replace ytdl
                    CurrentVersion = ytdlManager.Versions.Keys.Max();
                    ytdl           = ytdlManager.Versions[CurrentVersion];
                    log.LogInformation("Update to {0} completed.", CurrentVersion);
                }
            }
            else
            {
                log.LogInformation("No new version found!");
            }

            // Delete old versions which are no longer required
            log.LogInformation("Cleaning up old youtube-dl versions...");
            await ytdlManager.CleanupOldVersions(2);
        }
Ejemplo n.º 15
0
        private static void SetupDownload(YoutubeDL ydl)
        {
            ydl.process = new Process {
                StartInfo = ydl.processStartInfo, EnableRaisingEvents = true
            };

            ydl.stdOutputTokenSource = new CancellationTokenSource();
            ydl.stdErrorTokenSource  = new CancellationTokenSource();

            ydl.process.Exited += (sender, args) => ydl.KillProcess();

            // Note that synchronous calls are needed in order to process the output line by line.
            // Asynchronous output reading results in batches of output lines coming in all at once.
            // The following two threads convert synchronous output reads into asynchronous events.

            ThreadPool.QueueUserWorkItem(ydl.StandardOutput, ydl.stdOutputTokenSource.Token);
            ThreadPool.QueueUserWorkItem(ydl.StandardError, ydl.stdErrorTokenSource.Token);

            if (ydl.Info != null)
            {
                ydl.StandardOutputEvent += (sender, output) => ydl.Info.ParseOutput(sender, output.Trim());
                ydl.StandardErrorEvent  += (sender, output) => ydl.Info.ParseError(sender, output.Trim());
            }

            ydl.process.Start();
        }
Ejemplo n.º 16
0
        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();
        }
Ejemplo n.º 17
0
 public MediaEntry(YoutubeDL ydl, VideoData metadata, OptionSet overrideOptions = null)
 {
     this.ydl             = ydl;
     this.Metadata        = metadata;
     this.OverrideOptions = overrideOptions;
     this.progress        = new Progress <DownloadProgress>(p => RaiseDownloadStateChanged(p));
 }
Ejemplo n.º 18
0
        /// 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
        }
Ejemplo n.º 19
0
 public YoutubeDlService(DownloadQueueService queueService, StreamableUploadService streamableService)
 {
     _queueService      = queueService;
     _streamableService = streamableService;
     _youtubeDl         = new();
     _youtubeDl.Options.FilesystemOptions.Output = "/app/video.mp4";
 }
Ejemplo n.º 20
0
        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();
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     Asynchronously retrieve video / playlist information
        /// </summary>
        /// <param name="ydl">
        ///     The client
        /// </param>
        /// <param name="url">
        ///     URL of video / playlist
        /// </param>
        /// <param name="cancellationToken">
        ///     The cancellation token
        /// </param>
        /// <returns>
        ///     An object containing the download information
        /// </returns>
        internal static async Task <DownloadInfo> GetDownloadInfoAsync(this YoutubeDL ydl, string url, CancellationToken cancellationToken)
        {
            ydl.VideoUrl = url;
            await GetDownloadInfoAsync(ydl, cancellationToken);

            return(ydl.Info);
        }
Ejemplo n.º 22
0
        private async Task <VideoQualityFormat> getVideoFormatsAsync(string url)
        {
            VideoQualityFormat data = null;

            var updateGUIThread = new Progress <string>((value) =>
            {
            });


            var updateMainForm = updateGUIThread as IProgress <string>;


            await Task.Run(() => {
                string x = "";

                var youtubeDL1 = new YoutubeDL();
                youtubeDL1.StandardOutputEvent += (sender, output) => {
                    Console.WriteLine(output);
                    x = output;
                };
                youtubeDL1.StandardErrorEvent += (sender, errorOutput) => Console.WriteLine(errorOutput);
                youtubeDL1.VideoUrl            = _VODObject.url;
                youtubeDL1.Options.VerbositySimulationOptions.DumpJson = true;

                //Only can do one json even at a time
                youtubeDL1.Download();

                data = JsonConvert.DeserializeObject <VideoQualityFormat>(x);
            });


            return(data);
        }
Ejemplo n.º 23
0
        private static void SetInfoOptions(YoutubeDL ydl)
        {
            Options infoOptions = new Options
            {
                VerbositySimulationOptions =
                {
                    DumpSingleJson = true,
                    Simulate       = true
                },
                GeneralOptions =
                {
                    FlatPlaylist = !ydl.RetrieveAllInfo,
                    IgnoreErrors = true
                },
                AuthenticationOptions =
                {
                    Username      = ydl.Options.AuthenticationOptions.Username,
                    Password      = ydl.Options.AuthenticationOptions.Password,
                    NetRc         = ydl.Options.AuthenticationOptions.NetRc,
                    VideoPassword = ydl.Options.AuthenticationOptions.VideoPassword,
                    TwoFactor     = ydl.Options.AuthenticationOptions.TwoFactor
                },
                VideoSelectionOptions =
                {
                    NoPlaylist = ydl.Options.VideoSelectionOptions.NoPlaylist
                }
            };

            ydl.Options = infoOptions;
        }
        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]);
        }
        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 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);
        }
Ejemplo n.º 27
0
        static string VideoDownload(string url)
        {
            var youtubeDl = new YoutubeDL();

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                youtubeDl.YoutubeDlPath = "./tools/youtube-dl.exe";
            }
            else
            {
                youtubeDl.YoutubeDlPath = "./tools/youtube-dl";
            }
            string filename = url.Split("/")[url.Split("/").Length - 2] + ".mp4";

            youtubeDl.Options.FilesystemOptions.Output = filename;
            youtubeDl.VideoUrl = "https://reddit.com" + url;
            Console.WriteLine("https://reddit.com" + url);
            youtubeDl.StandardOutputEvent += (sender, output) => Console.WriteLine(output);
            youtubeDl.StandardErrorEvent  += (sender, errorOutput) => Console.WriteLine(errorOutput);
            string commandToRun = youtubeDl.PrepareDownload();

            youtubeDl.Download();
            youtubeDl = null;
            return(filename);
        }
        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("&amp;", "&");
                            path = path.Replace("|", "_");
                            path = path.Replace("*", "_");
                            path = path.Replace("/", "_");
                            path = path.Replace(@"\", "_");
                            path = path.Replace(":", "_");
                            path = path.Replace("?", "_");
                            path = path.Replace("&quot;", "'");
                        } // 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("Ошибки случаются");
                }
            }
        }
Ejemplo n.º 29
0
        public void TestIsPlaylistDownload()
        {
            YoutubeDL ydlClient = new YoutubeDL();

            var info = ydlClient.GetDownloadInfo(@"https://www.youtube.com/playlist?list=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-");

            Assert.NotNull(info as PlaylistDownloadInfo);
        }
Ejemplo n.º 30
0
        public void TestIsVideoDownload()
        {
            YoutubeDL ydlClient = new YoutubeDL();

            var info = ydlClient.GetDownloadInfo(@"https://www.youtube.com/watch?v=dQw4w9WgXcQ");

            Assert.NotNull(info as VideoDownloadInfo);
        }