//Methods
        public async void RunDownloads()
        {
            Console.WriteLine("RunDownloads Started");

            while (true)
            {
                MainWindow.SaveDownloads();

                cts = new CancellationTokenSource();

                List <Download> incompleteDownloads = new List <Download>();

                foreach (Download download in downloads)
                {
                    if (download.Status == "Queued")
                    {
                        incompleteDownloads.Add(download);
                    }
                }

                Console.WriteLine("Checking for Downloads...");

                if (incompleteDownloads.Count >= 1)
                {
                    Download currentDownload = incompleteDownloads[0];
                    currentDownload.IsAlive = true;

                    if ((currentDownload.YoutubeID != "") && (currentDownload.YoutubeID != null))
                    {
                        string itemUrl = "https://www.youtube.com/watch?v=" + currentDownload.YoutubeID;

                        try
                        {
                            if (Properties.Settings.Default.enableLocalYouTubeDownload)
                            {
                                await CustomLevelService.CreateWithLocalMP3Download(itemUrl, currentDownload, httpClient, cts);
                            }
                            else
                            {
                                await DownloadManager.RetrieveMetaData(itemUrl, currentDownload);
                            }
                        }
                        catch
                        {
                            currentDownload.Status = "Unable To Retrieve Metadata";
                        }

                        currentDownload.IsAlive = false;
                        cts.Dispose();
                    }
                    else if ((currentDownload.FilePath != "") && (currentDownload.FilePath != null))
                    {
                        try
                        {
                            await CustomLevelService.CreateFromFile(currentDownload, httpClient, cts);
                        }
                        catch
                        {
                            currentDownload.Status = "Unable To Create Level";
                        }

                        currentDownload.IsAlive = false;
                        cts.Dispose();
                    }
                }

                cts.Dispose();
                System.Threading.Thread.Sleep(1000);
            }
        }
        public void AddDownloads(object sender, RoutedEventArgs e)
        {
            if (DownloadManager.downloads.Count >= 100)
            {
                RaiseAnError("Maximum of 100 Downloads Reached");

                return;
            }

            DownloadManager downloadManager = MainWindow.downloadManager;

            string selectedDifficulties = "";
            string selectedGameModes    = "";
            string selectedSongEvents   = "";
            string selectedEnvironment  = "";
            string selectedModelVersion = "";

            bool difficultySelected = false;
            bool gameModeSelected   = false;

            if ((DifficultyNormalCheckBox.IsChecked == true) || (DifficultyHardCheckBox.IsChecked == true) || (DifficultyExpertCheckBox.IsChecked == true) || (DifficultyExpertPlusCheckBox.IsChecked == true))
            {
                difficultySelected = true;
            }

            if ((GameModeStandardCheckBox.IsChecked == true) || (GameModeOneSaberCheckBox.IsChecked == true) || (GameModeNoArrowsCheckBox.IsChecked == true) || (GameMode90DegreesCheckBox.IsChecked == true) || (GameMode360DegreesCheckBox.IsChecked == true))
            {
                gameModeSelected = true;
            }

            if (difficultySelected == true)
            {
                if (DifficultyExpertCheckBox.IsChecked == true)
                {
                    selectedDifficulties += "Expert,";
                }

                if (DifficultyExpertPlusCheckBox.IsChecked == true)
                {
                    selectedDifficulties += "ExpertPlus,";
                }

                if (DifficultyNormalCheckBox.IsChecked == true)
                {
                    selectedDifficulties += "Normal,";
                }

                if (DifficultyHardCheckBox.IsChecked == true)
                {
                    selectedDifficulties += "Hard,";
                }

                if (selectedDifficulties[selectedDifficulties.Count() - 1] == ',')
                {
                    selectedDifficulties = selectedDifficulties.Remove(selectedDifficulties.Count() - 1);

                    Properties.Settings.Default.previousDifficulties = selectedDifficulties;
                    Properties.Settings.Default.Save();
                }
            }
            else
            {
                Console.WriteLine("Please Select at Least One Difficulty");

                RaiseAnError("Please Select at Least One Difficulty");

                return;
            }

            if (gameModeSelected == true)
            {
                if (GameModeStandardCheckBox.IsChecked == true)
                {
                    selectedGameModes += "Standard,";
                }

                if (GameMode90DegreesCheckBox.IsChecked == true)
                {
                    selectedGameModes += "90Degree,";
                }

                if (GameModeNoArrowsCheckBox.IsChecked == true)
                {
                    selectedGameModes += "NoArrows,";
                }

                if (GameModeOneSaberCheckBox.IsChecked == true)
                {
                    selectedGameModes += "OneSaber,";
                }

                if (GameMode360DegreesCheckBox.IsChecked == true)
                {
                    selectedGameModes += "360Degree,";
                }

                if (selectedGameModes[selectedGameModes.Count() - 1] == ',')
                {
                    selectedGameModes = selectedGameModes.Remove(selectedGameModes.Count() - 1);

                    Properties.Settings.Default.previousGameModes = selectedGameModes;
                    Properties.Settings.Default.Save();
                }
            }
            else
            {
                Console.WriteLine("Please Select at Least One Game Mode");

                RaiseAnError("Please Select at Least One Game Mode");

                return;
            }

            if (SongEventDotBlocksCheckBox.IsChecked == true)
            {
                selectedSongEvents += "DotBlocks,";
            }

            if (SongEventsObstaclesCheckBox.IsChecked == true)
            {
                selectedSongEvents += "Obstacles,";
            }

            if (SongEventsBombsCheckBox.IsChecked == true)
            {
                selectedSongEvents += "Bombs,";
            }

            if (SongEventsLightShowCheckBox.IsChecked == true)
            {
                selectedSongEvents += "LightShow,";
            }

            if ((selectedSongEvents != "") && (selectedSongEvents[selectedSongEvents.Count() - 1] == ','))
            {
                selectedSongEvents = selectedSongEvents.Remove(selectedSongEvents.Count() - 1);
            }

            List <string> songEnvironments = new List <string>();

            foreach (ComboBoxItem comboBoxItem in EnvironmentComboBox.Items)
            {
                if (!comboBoxItem.Tag.ToString().Contains("Random"))
                {
                    songEnvironments.Add(comboBoxItem.Tag.ToString());
                    songEnvironments.Add(comboBoxItem.Tag.ToString());
                }
            }

            Properties.Settings.Default.previousEnvironment  = EnvironmentComboBox.Text;
            Properties.Settings.Default.previousModelVersion = ModelVersionComboBox.Text;
            Properties.Settings.Default.previousGameEvents   = selectedSongEvents;
            Properties.Settings.Default.Save();

            selectedEnvironment = GetSelectedEnvironment();

            Random random = new Random();

            if (selectedEnvironment == "Random")
            {
                int randomItemIndex = random.Next(songEnvironments.Count);
                selectedEnvironment = songEnvironments[randomItemIndex];
                Console.WriteLine("Random Environment: " + selectedEnvironment);
            }

            selectedModelVersion = GetSelectedModelVersion();

            loadingLabel.Visibility = Visibility.Visible;

            for (int i = 0; i < linksTextBox.LineCount; i++)
            {
                if (DownloadManager.downloads.Count >= 100)
                {
                    RaiseAnError("Maximum of 100 Downloads Reached");

                    loadingLabel.Visibility = Visibility.Hidden;
                    return;
                }

                if (linksTextBox.GetLineText(i).Replace(" ", "").Replace("\n", "").Replace("\r", "").Count() < 5)
                {
                    continue;
                }

                if (GetSelectedEnvironment() == "RandomPerSong")
                {
                    int randomItemIndex = random.Next(songEnvironments.Count);
                    selectedEnvironment = songEnvironments[randomItemIndex];
                    Console.WriteLine("Random Per Song Environment: " + selectedEnvironment);
                }

                if ((linksTextBox.GetLineText(i).Contains("youtube.com/watch?v=")) || (linksTextBox.GetLineText(i).Contains("https://youtu.be/")))
                {
                    string youtubeID = linksTextBox.GetLineText(i).Replace("https://youtu.be/", "").Replace("music.", "www.").Replace("https://www.youtube.com/watch?v=", "").TrimEnd('\r', '\n');

                    if (youtubeID.Contains("&"))
                    {
                        youtubeID = youtubeID.Substring(0, youtubeID.IndexOf("&"));
                    }

                    Console.WriteLine("Youtube ID: " + youtubeID);

                    MainWindow.downloadManager.Add(new Download()
                    {
                        Number       = DownloadManager.downloads.Count + 1,
                        YoutubeID    = youtubeID,
                        Title        = "???",
                        Artist       = "???",
                        Status       = "Queued",
                        Difficulties = selectedDifficulties,
                        GameModes    = selectedGameModes,
                        SongEvents   = selectedSongEvents,
                        FilePath     = "",
                        FileName     = "",
                        Environment  = selectedEnvironment,
                        ModelVersion = selectedModelVersion,
                        IsAlive      = false
                    });
                }
                else if (linksTextBox.GetLineText(i).Contains(".mp3"))
                {
                    string filePath = linksTextBox.GetLineText(i).TrimEnd('\r', '\n');

                    Console.WriteLine("File Path: " + filePath);

                    MainWindow.downloadManager.Add(new Download()
                    {
                        Number       = DownloadManager.downloads.Count + 1,
                        YoutubeID    = "",
                        Title        = "???",
                        Artist       = "???",
                        Status       = "Queued",
                        Difficulties = selectedDifficulties,
                        GameModes    = selectedGameModes,
                        SongEvents   = selectedSongEvents,
                        FilePath     = filePath,
                        FileName     = System.IO.Path.GetFileName(filePath),
                        Environment  = selectedEnvironment,
                        ModelVersion = selectedModelVersion,
                        IsAlive      = false
                    });
                }
            }

            loadingLabel.Visibility = Visibility.Hidden;
            this.Close();
        }
Exemplo n.º 3
0
 public async void CheckUpdateAvailable()
 {
     await DownloadManager.CheckUpdateAvailable();
 }
        public static async Task Create(JObject responseData, Download download, HttpClient httpClient, CancellationTokenSource cts)
        {
            download.Status = "Generating Custom Level";

            string trackName = "Unknown";

            if (((string)responseData["track"]) != null)
            {
                trackName = (string)responseData["track"];
            }
            else if (((string)responseData["fulltitle"]) != null)
            {
                trackName = (string)responseData["fulltitle"];
            }

            string artistName = "Unknown";

            if (((string)responseData["artist"]) != null)
            {
                artistName = (string)responseData["artist"];
            }
            else if (((string)responseData["uploader"]) != null)
            {
                artistName = (string)responseData["uploader"];
            }

            var invalids = System.IO.Path.GetInvalidFileNameChars();

            trackName  = String.Join("_", trackName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            artistName = String.Join("_", artistName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');

            Console.WriteLine("trackName: " + trackName);
            Console.WriteLine("artistName: " + artistName);

            download.Title  = trackName;
            download.Artist = artistName;

            string fileName = "[BSD] " + trackName + " - " + artistName;

            if (!Properties.Settings.Default.overwriteExisting)
            {
                if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName))))
                {
                    download.Status  = "Already Exists";
                    download.IsAlive = false;
                    return;
                }
            }

            Console.WriteLine("download.Title: " + download.Title);
            Console.WriteLine("download.Artist : " + download.Artist);

            string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms";
            var    content  = new MultipartFormDataContent(boundary);

            content.Add(new StringContent((string)responseData["webpage_url"]), "youtube_url");

            var imageContent = new ByteArrayContent((byte[])responseData["beatsage_thumbnail"]);

            imageContent.Headers.Remove("Content-Type");
            imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\"");
            imageContent.Headers.Add("Content-Type", "image/jpeg");
            content.Add(imageContent);

            content.Add(new StringContent(trackName), "audio_metadata_title");
            content.Add(new StringContent(artistName), "audio_metadata_artist");
            content.Add(new StringContent(download.Difficulties), "difficulties");
            content.Add(new StringContent(download.GameModes), "modes");
            content.Add(new StringContent(download.SongEvents), "events");
            content.Add(new StringContent(download.Environment), "environment");
            content.Add(new StringContent(download.ModelVersion), "system_tag");

            var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token);

            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);

            JObject jsonString = JObject.Parse(responseString);

            string levelID = (string)jsonString["id"];

            Console.WriteLine(levelID);

            await DownloadManager.CheckDownload(levelID, trackName, artistName, download);
        }
        public static async Task CreateFromFile(Download download, HttpClient httpClient, CancellationTokenSource cts)
        {
            download.Status = "Uploading File";

            TagLib.File tagFile = TagLib.File.Create(download.FilePath);

            string artistName = "Unknown";

            byte[] imageData = null;

            var invalids = System.IO.Path.GetInvalidFileNameChars();

            if (tagFile.Tag.FirstPerformer != null)
            {
                artistName = String.Join("_", tagFile.Tag.FirstPerformer.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }

            string trackName;

            if (tagFile.Tag.Title != null)
            {
                trackName = String.Join("_", tagFile.Tag.Title.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }
            else
            {
                trackName = System.IO.Path.GetFileNameWithoutExtension(download.FilePath);
            }

            if (tagFile.Tag.Pictures.Count() > 0)
            {
                if (tagFile.Tag.Pictures[0].Data.Data != null)
                {
                    imageData = tagFile.Tag.Pictures[0].Data.Data;
                }
            }


            download.Artist = artistName;
            download.Title  = trackName;

            string fileName = "[BSD] " + trackName + " - " + artistName;

            if (!Properties.Settings.Default.overwriteExisting)
            {
                if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName))))
                {
                    download.Status  = "Already Exists";
                    download.IsAlive = false;
                    return;
                }
            }

            byte[] bytes = File.ReadAllBytes(download.FilePath);

            string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms";
            var    content  = new MultipartFormDataContent(boundary);

            content.Add(new ByteArrayContent(bytes), "audio_file", download.FileName);

            if (imageData != null)
            {
                var imageContent = new ByteArrayContent(imageData);
                imageContent.Headers.Remove("Content-Type");
                imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\"");
                imageContent.Headers.Add("Content-Type", "image/jpeg");
                content.Add(imageContent);
            }

            content.Add(new StringContent(trackName), "audio_metadata_title");
            content.Add(new StringContent(artistName), "audio_metadata_artist");
            content.Add(new StringContent(download.Difficulties), "difficulties");
            content.Add(new StringContent(download.GameModes), "modes");
            content.Add(new StringContent(download.SongEvents), "events");
            content.Add(new StringContent(download.Environment), "environment");
            content.Add(new StringContent(download.ModelVersion), "system_tag");

            var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token);

            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);

            JObject jsonString = JObject.Parse(responseString);

            string levelID = (string)jsonString["id"];

            Console.WriteLine(levelID);

            await DownloadManager.CheckDownload(levelID, trackName, artistName, download);
        }
        public async static Task CreateWithLocalMP3Download(string url, Download download, HttpClient httpClient, CancellationTokenSource cts)
        {
            download.Status = "Downloading File";

            var youtube = new YoutubeClient();

            // You can specify video ID or URL
            var video = await youtube.Videos.GetAsync(url);

            var duration = video.Duration; // 00:07:14

            if (video.Duration.Minutes + (video.Duration.Seconds / 60) > 10)
            {
                return;
            }

            string artistName = "Unknown";
            string trackName  = "Unknown";

            var invalids = System.IO.Path.GetInvalidFileNameChars();

            if (video.Author != null)
            {
                artistName = String.Join("_", video.Author.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }

            if (video.Title != null)
            {
                trackName = String.Join("_", video.Title.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }

            download.Artist = artistName;
            download.Title  = trackName;

            string fileName = "[BSD] " + trackName + " - " + artistName;

            download.FilePath = fileName + ".mp3";

            if (!Properties.Settings.Default.overwriteExisting)
            {
                if (((!Properties.Settings.Default.automaticExtraction) && (File.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName + ".zip"))) || ((Properties.Settings.Default.automaticExtraction) && (Directory.Exists(Properties.Settings.Default.outputDirectory + @"\" + fileName))))
                {
                    download.Status  = "Already Exists";
                    download.IsAlive = false;
                    return;
                }
            }

            var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id);

            var streamInfo = streamManifest.GetAudioOnly().WithHighestBitrate();

            if (streamInfo != null)
            {
                // Get the actual stream
                _ = await youtube.Videos.Streams.GetAsync(streamInfo);

                // Download the stream to file
                await youtube.Videos.Streams.DownloadAsync(streamInfo, fileName + ".mp3");
            }

            string boundary = "----WebKitFormBoundaryaA38RFcmCeKFPOms";
            var    content  = new MultipartFormDataContent(boundary);

            byte[] bytes = System.IO.File.ReadAllBytes(download.FilePath);

            if (File.Exists(download.FilePath))
            {
                File.Delete(download.FilePath);
            }

            content.Add(new ByteArrayContent(bytes), "audio_file", download.FilePath);

            using (WebClient client = new WebClient())
            {
                try
                {
                    client.DownloadFile(new Uri("https://img.youtube.com/vi/" + video.Id + "/maxresdefault.jpg"), "cover.jpg");
                }
                catch
                {
                    try
                    {
                        client.DownloadFile(new Uri("https://img.youtube.com/vi/" + video.Id + "/sddefault.jpg"), "cover.jpg");
                    }
                    catch
                    {
                        try
                        {
                            client.DownloadFile(new Uri("https://img.youtube.com/vi/" + video.Id + "/hqdefault.jpg"), "cover.jpg");
                        }
                        catch
                        {
                        }
                    }
                }
            }

            byte[] imageData = System.IO.File.ReadAllBytes("cover.jpg");

            if (imageData != null)
            {
                var imageContent = new ByteArrayContent(imageData);
                imageContent.Headers.Remove("Content-Type");
                imageContent.Headers.Add("Content-Disposition", "form-data; name=\"cover_art\"; filename=\"cover\"");
                imageContent.Headers.Add("Content-Type", "image/jpeg");
                content.Add(imageContent);
            }

            if (File.Exists("cover.jpg"))
            {
                File.Delete("cover.jpg");
            }

            content.Add(new StringContent(trackName), "audio_metadata_title");
            content.Add(new StringContent(artistName), "audio_metadata_artist");
            content.Add(new StringContent(download.Difficulties), "difficulties");
            content.Add(new StringContent(download.GameModes), "modes");
            content.Add(new StringContent(download.SongEvents), "events");
            content.Add(new StringContent(download.Environment), "environment");
            content.Add(new StringContent(download.ModelVersion), "system_tag");

            var response = await httpClient.PostAsync("https://beatsage.com/beatsaber_custom_level_create", content, cts.Token);

            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);

            JObject jsonString = JObject.Parse(responseString);

            string levelID = (string)jsonString["id"];

            Console.WriteLine(levelID);

            await DownloadManager.CheckDownload(levelID, trackName, artistName, download);
        }