示例#1
0
        public void btnGet_Click(object sender, EventArgs e)
        {
            string url = this.txtURL.Text;

            string[] videoURLs;

            try
            {
                videoURLs    = new string[1];
                videoURLs[0] = txtURL.Text;
//                List<YouTubeVideoQuality> urls = YouTubeVideoDownloader.GetYouTubeVideoUrls(videoURLs);
                List <YouTube_Downloader.YouTubeVideoQuality> urls = YouTubeDownloader.GetYouTubeVideoUrls(videoURLs);

                cbxQuality.Items.Clear();

                foreach (var items in urls)
                {
                    cbxQuality.Items.Add(items);
                    string videoTitle = items.VideoTitle;
                    txtTitle.Text = videoTitle;
                }
                this.btnDownload.Enabled = true;
            }
            catch
            {
                this.btnDownload.Enabled = true;
                MessageBox.Show("Load Failed!");
            }
        }
示例#2
0
 private void OnMenuSceneLoadedFresh()
 {
     YouTubeDownloader.OnLoad();
     ScreenManager.OnLoad();
     VideoLoader.OnLoad();
     VideoMenu.instance.OnLoad();
 }
示例#3
0
        static void Main(string[] args)
        {
            Client client = new Client();

            Console.WriteLine("Client: Executing the client code with a real subject:");
            RealSubject realSubject = new RealSubject();

            client.ClientCode(realSubject);

            Console.WriteLine();

            Console.WriteLine("Client: Executing the same client code with a proxy:");
            Proxy proxy = new Proxy(realSubject);

            client.ClientCode(proxy);

            Console.WriteLine("Practical Part: YouTubeCacheProxy");

            YouTubeDownloader naiveDownloader = new YouTubeDownloader(new ThirdPartyYouTubeClass());
            YouTubeDownloader smartDownloader = new YouTubeDownloader(new YouTubeCacheProxy());

            Console.WriteLine("---naiveDownloader --- start--");
            TimeSpan naive = Test(naiveDownloader);

            Console.WriteLine("---naiveDownloader --- end--");
            Console.WriteLine("---smartDownloader --- start--");
            TimeSpan smart = Test(smartDownloader);

            Console.WriteLine("---smartDownloader --- end--");
            Console.WriteLine("Time saved by caching proxy: " + (naive - smart) + "ms");
        }
示例#4
0
        // private void OnMenuSceneLoaded()
        // {
        //     ScreenManager.OnLoad();
        // }

        private static void OnMenuSceneLoadedFresh(ScenesTransitionSetupDataSO scenesTransition)
        {
            YouTubeDownloader.OnLoad();
            ScreenManager.OnLoad();
            VideoLoader.OnLoad();
            VideoMenu.instance.OnLoad();
        }
示例#5
0
        public async Task <AbstractDownloadState?> Infer(Uri uri)
        {
            var state = YouTubeDownloader.UriToState(uri) as YouTubeDownloader.State;

            if (state == null)
            {
                return(null);
            }

            var client = new YoutubeClient(Common.Http.ClientFactory.Client);
            var video  = await client.Videos.GetAsync(state.Key);

            var desc = video.Description;

            var replaceChars = new HashSet <char>()
            {
                '_', '(', ')', '-'
            };

            var lines = desc.Split('\n', StringSplitOptions.RemoveEmptyEntries)
                        .Select(line => line.Trim())
                        .Select(line =>
            {
                var segments = replaceChars.Aggregate(line, (acc, c) => acc.Replace(c, ' '))
                               .Split(' ', StringSplitOptions.RemoveEmptyEntries);
                if (segments.Length == 0)
                {
                    return(TimeSpan.Zero, string.Empty);
                }

                foreach (var segment in segments)
                {
                    if (TryParseEx(segment, out var si))
                    {
                        return(si, string.Join(" ", segments.Where(s => !s.Contains(":"))));
                    }
                }
                return(TimeSpan.Zero, string.Empty);
            })
                        .Where(t => t.Item2 != string.Empty)
                        .ToList();

            var tracks = lines.Select((line, idx) => new YouTubeDownloader.State.Track
            {
                Name   = Sanitize(line.Item2),
                Start  = line.Item1,
                End    = idx < lines.Count - 1 ? lines[idx + 1].Item1 : video.Duration,
                Format = YouTubeDownloader.State.Track.FormatEnum.XWM
            }).ToList();

            foreach (var track in tracks)
            {
                Utils.Log($"Inferred Track {track.Name} {track.Format} {track.Start}-{track.End}");
            }

            state.Tracks = tracks;

            return(state);
        }
示例#6
0
 private void OnMenuSceneLoadedFresh()
 {
     YouTubeDownloader.OnLoad();
     VideoUI.Instance.OnLoad();
     ScreenManager.OnLoad();
     VideoLoader.OnLoad();
     CreateSettingsUI();
 }
示例#7
0
文件: Program.cs 项目: l4km47/ytd
        private static void DownloadVideo(string url, string fileName)
        {
            Console.WriteLine("* Download YourTube video");

            Console.WriteLine("Fetching video informations ...");
            List <YouTubeVideoQuality> videoList = YouTubeDownloader.GetYouTubeVideoUrls(url);

            if (videoList.Count > 0)
            {
                downloadDone = new ManualResetEvent(false);

                YouTubeVideoQuality video = GetPreferred(videoList);

                if (video != null)
                {
                    string fn = fileName;

                    if (string.IsNullOrEmpty(fn))
                    {
                        fn = string.Concat(video.VideoTitle, ".", video.Extention);
                    }

                    Console.WriteLine("url: {0}", url);
                    Console.WriteLine("fileName: \"{0}\"", fn);

                    if (File.Exists(fn))
                    {
                        Console.Write("\"{0}\" already exists! Overwrite? (y/N) ", fn);
                        char res = ConsoleEx.ReadKey(5, 'n');
                        if (res.Equals('n'))
                        {
                            File.Delete(fn);
                        }
                        else
                        {
                            return;
                        }
                    }

                    downloadDone.Reset();
                    Console.WriteLine("Video Title: \"{0}\"", video.VideoTitle);
                    Console.WriteLine("File lenght: {0}", new FileSize(video.VideoSize).ToString(FileSizeUnit.B));
                    Console.WriteLine("* Downloading {0} => \"{1}\"", ConsoleEx.CompactPath(video.DownloadUrl, 40), ConsoleEx.CompactPath(fileName, 40));
                    DownloadFile(video.DownloadUrl, fn);
                    downloadDone.WaitOne();
                }
                else
                {
                    Console.WriteLine("No video match conditions!");
                }
            }
            else
            {
                Console.WriteLine("The <url> specified doesn't contain videos");
            }
        }
示例#8
0
 internal SongCollection(LiteDatabase db, ILoggerFactory loggerFactory, Configuration config, IServiceProvider services)
 {
     logger     = loggerFactory.CreateLogger <SongCollection>();
     collection = db.GetCollection <SongData>();
     collection.EnsureIndex(d => d.Id);
     collection.EnsureIndex(d => d.LastAccess);
     fileStorage = db.FileStorage;
     downloader  = new YouTubeDownloader(services.GetRequiredService <IMusicEncoderService>());
     this.config = config;
 }
示例#9
0
        public async Task <AbstractDownloadState?> Infer(Uri uri)
        {
            var state = YouTubeDownloader.UriToState(uri) as YouTubeDownloader.State;

            if (state == null)
            {
                return(null);
            }

            var client = new YoutubeClient(Common.Http.ClientFactory.Client);
            var video  = await client.Videos.GetAsync(state.Key);

            var desc = video.Description;

            var lines = desc.Split('\n', StringSplitOptions.RemoveEmptyEntries)
                        .Select(line => line.Trim())
                        .Select(line =>
            {
                var segments = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
                if (segments.Length == 0)
                {
                    return(TimeSpan.Zero, string.Empty);
                }

                if (TryParseEx(segments.First(), out var s1))
                {
                    return(s1, string.Join(" ", segments.Skip(1)));
                }
                if (TryParseEx(Enumerable.Last(segments), out var s2))
                {
                    return(s2, string.Join(" ", Utils.ButLast(segments)));
                }
                return(TimeSpan.Zero, string.Empty);
            })
                        .Where(t => t.Item2 != null)
                        .ToList();

            var tracks = lines.Select((line, idx) => new YouTubeDownloader.State.Track
            {
                Name   = Sanitize(line.Item2),
                Start  = line.Item1,
                End    = idx < lines.Count - 1 ? lines[idx + 1].Item1 : video.Duration,
                Format = YouTubeDownloader.State.Track.FormatEnum.XWM
            }).ToList();

            state.Tracks = tracks;

            return(state);
        }
示例#10
0
        private static TimeSpan Test(YouTubeDownloader downloader)
        {
            var startTime = DateTime.Now;

            // User behavior in our app:
            downloader.RenderPopularVideos();
            downloader.RenderVideoPage("catzzzzzzzzz");
            downloader.RenderPopularVideos();
            downloader.RenderVideoPage("dancesvideoo");
            // Users might visit the same page quite often.
            downloader.RenderVideoPage("catzzzzzzzzz");
            downloader.RenderVideoPage("someothervid");

            var estimatedTime = DateTime.Now - startTime;

            Console.WriteLine("Time elapsed: " + estimatedTime + "ms\n");
            return(estimatedTime);
        }
示例#11
0
        public async void DownloadUrlsDelegate()
        {
            //Make checks from user before downloading songs
            if (MusicManager.Instance.PlayLists.Count == 0)
            {
                var dialog = new ErrorDialog("There are no avaliable playlists! Please make one");
                dialog.ShowDialog();
                return;
            }
            else if (Urls.Count == 0)
            {
                var dialog = new ErrorDialog("You have not selected any songs to download!");
                dialog.ShowDialog();
                return;
            }
            PlayList playlist = RunSelectPlayListDialog();

            if (playlist != null)
            {
                string[] downloadUrls = Urls.Select(url => url.Item1).ToArray();
                string[] AddedSongs   = null;
                await Task.Run(() =>
                {
                    try
                    {
                        AddedSongs = YouTubeDownloader.DownloadSongs(downloadUrls);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error Downloading songs! Err : {0} ", e);
                    }
                });

                bool?worked = null;
                if (AddedSongs != null)
                {
                    worked = MusicManager.Instance.AddSongs(playlist.DisplayName, AddedSongs);
                }
                Console.WriteLine(worked);
            }
        }
示例#12
0
        //Make youtube process with my special parser to avoid stdout buffer overflows
        public static IEnumerator SearchYoutubeWithMyExeCoroutine(string query, Action callback, int resultsNumber = 5)
        {
            //If query is the same as the last one or the same as the default one I ran when the level was loaded, just wait for that to finish and use it
            if (searchResults != null && searchResults.query == query)
            {
                Plugin.logger.Debug("Waiting for other search");
                yield return(new WaitUntil(() => searchResults.isDone || searchResults.Count >= 5 || searchResults.query != query));

                Plugin.logger.Debug("Done Waiting for other search");
            }
            else
            {
                searchResults = new SearchResults(query);
                Plugin.logger.Debug("Starting Search");
                var searchProcess = new Process
                {
                    StartInfo =
                    {
                        // #define USEYTDLHELPER
#if USEYTDLHELPER
                        FileName  = Environment.CurrentDirectory + "/Youtube-dl/SelectJsonFromYoutubeDL.exe",
                        Arguments =
                            $"\"{Environment.CurrentDirectory + "/Youtube-dl/youtube-dl.exe"}\" \"{query}\" {resultsNumber}",
#else
                        FileName  = Environment.CurrentDirectory + "/Youtube-dl/youtube-dl.exe",
                        Arguments = $"\"ytsearch{resultsNumber}:{query}\" -j -i",
#endif
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        UseShellExecute        = false,
                        CreateNoWindow         = true
                    },
                    EnableRaisingEvents = true,
                    //I think these are added only after Process Started
                    //PriorityClass = ProcessPriorityClass.RealTime,
                    PriorityBoostEnabled = true
                };
                Plugin.logger.Debug("Process Made");
                Plugin.logger.Info(
                    $"yt command: \"{searchProcess.StartInfo.FileName}\" {searchProcess.StartInfo.Arguments}");
                yield return(isReadingOutput = false);

                searchProcess.ErrorDataReceived += (sender, e) =>
                {
                    if (searchResults.query != query)
                    {
                        Plugin.logger.Debug("Killing Search Process");
                        try
                        {
                            searchProcess.Kill();
                        } catch { }

                        return;
                    }
                    if (e.Data == null)
                    {
                        return;
                    }

                    Plugin.logger.Error("Error With the process:");
                    Plugin.logger.Error(e.Data);
                };
                searchProcess.OutputDataReceived += (sender, e) =>
                {
                    if (searchResults.query != query)
                    {
                        Plugin.logger.Debug("Killing Search Process");
                        try
                        {
                            searchProcess.Kill();
                        } catch { }
                        return;
                    }

                    var output = e.Data.Trim();
                    if (string.IsNullOrWhiteSpace(output))
                    {
                        return;
                    }
                    else if (output.Contains("yt command exited"))
                    {
                        Plugin.logger.Debug("Done with Youtube Search, Processing...");
                        return;
                    }
                    else if (output.Contains("yt command"))
                    {
                        Plugin.logger.Debug($"Running with {output}");
                        return;
                    }
                    try
                    {
                        var      trimmedLine = output;
                        YTResult ytResult    = MakeYtResult(trimmedLine);
                        // Plugin.logger.Debug($"Adding: {ytResult.title}");
                        searchResults.Add(ytResult);
                        if (searchResults.Count >= resultsNumber)
                        {
                            try
                            {
                                ((Process)sender).Kill();
                            } catch {}
                        }
                    }
                    catch (Exception error)
                    {
                        Plugin.logger.Debug($"Invalid Response: {output}");
                        Plugin.logger.Error(error);
                    }
                };
                searchProcess.Exited += (sender, e) =>
                {
                    searchResults.isDone = true;
                    if (searchResults.Count != resultsNumber)
                    {
                        Plugin.logger.Warn($"Failed on {resultsNumber-searchResults.Count} queries with exitcode {((Process) sender).ExitCode}");
                    }
                    try
                    {
                        searchProcess.Kill();
                    } catch { }
                    try
                    {
                        searchProcess.Dispose();
                    } catch { }
                };
                // Plugin.logger.Debug("Error Set");
                yield return(searchProcess.Start());

                var fifteenSeconds = new TimeSpan(15 * TimeSpan.TicksPerSecond);
                var countdown      = YouTubeDownloader.Countdown(searchProcess, fifteenSeconds);
                SharedCoroutineStarter.instance.StartCoroutine(countdown);
                // Plugin.logger.Debug("started");
                searchProcess.BeginErrorReadLine();
                searchProcess.BeginOutputReadLine();
                // Plugin.logger.Debug("Error Reading");
                // var outputs = searchProcess.StandardOutput.ReadToEnd().Split('\n');
                yield return(new WaitUntil(() =>
                                           { try { return searchProcess.HasExited; } catch { return true; } }));

                SharedCoroutineStarter.instance.StopCoroutine(countdown);
                if (searchResults.query != query)
                {
                    yield break;
                }
                // foreach (var output in outputs)
                // {
                //     if (string.IsNullOrWhiteSpace(output))
                //     {
                //         continue;
                //     }
                //     else if (output.Contains("yt command exited"))
                //     {
                //         Plugin.logger.Debug("Done with Youtube Search, Processing...");
                //         continue;
                //     }
                //     else if (output.Contains("yt command"))
                //     {
                //         Plugin.logger.Debug($"Running with {output.Trim()}");
                //         continue;
                //     }
                //
                //     try
                //     {
                //         var trimmedLine = output.Trim();
                //         YTResult ytResult = MakeYtResult(trimmedLine);
                //         searchResults.Add(ytResult);
                //     }
                //     catch (Exception e)
                //     {
                //         Plugin.logger.Debug($"Invalid Response: {output.Trim()}");
                //         Plugin.logger.Error(e);
                //     }
                // }
                // Plugin.logger.Debug(searchResults.Count.ToString());
            }
            if (callback == null || query != searchResults.query)
            {
                yield break;
            }
            Plugin.logger.Debug($"Invoking Callback");
            callback?.Invoke();
            yield return(new WaitUntil((() => searchResults.isDone || searchResults.Count >= MaxResults)));

            callback?.Invoke();
            searchInProgress = false;
        }