Example #1
0
        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void downBtn_Click(object sender, EventArgs e)
        {
            try
            {
                toolStripProgressBar1.Value   = 0;
                toolStripProgressBar1.Visible = true;

                if (!Directory.Exists(target))
                {
                    Directory.CreateDirectory(target);
                }

                if (downloader == null)
                {
                    downloader = new SongDownloader(provider, target);
                }
                downloader.rate = this.cbRate.SelectedItem.ToString();

                foreach (ListViewItem item in resultListView.CheckedItems)
                {
                    timer1.Enabled  = true;
                    timer1.Interval = 500;
                    var song = (MergedSong)item.Tag;
                    downloader.AddDownload(song);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #2
0
        public void BeatSaverFavoriteMappers_Cancelled()
        {
            var config       = DefaultConfig;
            var sourceConfig = DefaultConfig.BeatSaver;

            sourceConfig.MaxConcurrentPageChecks = 5;
            var feedConfig = sourceConfig.FavoriteMappers;

            feedConfig.MaxSongs = 60;
            var songDownloader = new SongDownloader(config, null, null, SONGSPATH);
            var reader         = new BeatSaverReader();
            var settings       = (BeatSaverFeedSettings)feedConfig.ToFeedSettings();
            var queryBuilder   = new SearchQueryBuilder(BeatSaverSearchType.author, "Ruckus");

            settings.SearchQuery = queryBuilder.GetQuery();
            CancellationTokenSource cts = new CancellationTokenSource(150);
            var resultTask = songDownloader.ReadFeed(reader, settings, 0, null, PlaylistStyle.Append, cts.Token);


            var result = resultTask.Result;

            Assert.IsNotNull(result);
            Assert.IsFalse(result.Successful);
            Assert.AreEqual(FeedResultError.Cancelled, result.ErrorCode);
        }
Example #3
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                toolStripProgressBar1.Value   = 0;
                toolStripProgressBar1.Visible = true;
                IniFile ini = new IniFile(Application.StartupPath + "\\Config.ini");
                downPath = ini.ReadString("setting", "downloadPath", "D:\\MusicDownload\\");
                if (!Directory.Exists(downPath))
                {
                    Directory.CreateDirectory(downPath);
                }

                if (downloader == null)
                {
                    downloader = new SongDownloader(Source, downPath);
                }

                foreach (ListViewItem item in listViewResult.CheckedItems)
                {
                    timer.Enabled  = true;
                    timer.Interval = 500;
                    var song = (MergedSong)item.Tag;
                    downloader.AddDownload(song);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void DownLoadMusic_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var target = this.txtDownloadFilePah.Text;
                if (!Directory.Exists(target))
                {
                    Directory.CreateDirectory(target);
                }

                if (downloader == null)
                {
                    downloader = new SongDownloader(provider, target);
                }

                List <MergedSong> selectedData = new List <MergedSong>();
                for (int i = 0; i < resultListView.Items.Count; i++)
                {
                    var res = (MergedSong)resultListView.Items[i];
                    if (res.IsChecked)
                    {
                        selectedData.Add(res);
                    }
                }

                foreach (var item in selectedData)
                {
                    downloader.AddDownload(item);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
Example #5
0
        IEnumerator CheckVersion()
        {
            Plugin.log.Info("Checking for updates...");

            UnityWebRequest www = SongDownloader.GetRequestForUrl($"https://api.github.com/repos/andruzzzhka/BeatSaberMultiplayer/releases");

            www.timeout = 10;

            yield return(www.SendWebRequest());

            if (!www.isNetworkError && !www.isHttpError)
            {
                JSONNode releases = JSON.Parse(www.downloadHandler.text);

                JSONNode latestRelease = releases[0];

                SemVer.Version currentVer = IPA.Loader.PluginManager.GetPlugin("Beat Saber Multiplayer").Version;
                SemVer.Version githubVer  = new SemVer.Version(latestRelease["tag_name"], true);

                bool newTag = new SemVer.Range($">{currentVer}").IsSatisfied(githubVer);

                if (newTag)
                {
                    Plugin.log.Info($"An update for the mod is available!\nNew mod version: {(string)latestRelease["tag_name"]}\nCurrent mod version: {currentVer}");
                    _newVersionText.gameObject.SetActive(true);
                    _newVersionText.text      = $"Version {(string)latestRelease["tag_name"]}\n of the mod is available!\nCurrent mod version: {currentVer}";
                    _newVersionText.alignment = TextAlignmentOptions.Center;
                }
            }
        }
Example #6
0
        public ChorusSongListBoxItem(MainWindow mainWindow, Song song)
        {
            Content = song.artist + " - " + song.name + " (" + song.charter + ")";
            RemoteSongContextMenu contextMenu = new RemoteSongContextMenu();

            contextMenu.Download += () =>
            {
                string songsDirectory = mainWindow.SongsDirectory.Text;
                mainWindow.StatusLabel.Content = "Downloading...";
                Task.Run(() =>
                {
                    string link         = song.directLinks.archive ?? song.link;
                    bool downloadFailed = false;
                    try
                    {
                        SongDownloader.DownloadSong(songsDirectory, link, song.artist, song.name, song.charter, (status) =>
                        {
                            Dispatcher.Invoke(() => mainWindow.StatusLabel.Content = status);
                        });
                    }
                    catch (Win32Exception exception)
                    {
                        Dispatcher.Invoke(() => MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error));
                        downloadFailed = true;
                    }
                    catch (Exception e)
                    {
                        string message;
                        if (e is WebException)
                        {
                            message = e.InnerException?.Message ?? e.Message;
                        }
                        else
                        {
                            message = "Link could not be downloaded.";
                        }
                        downloadFailed = true;
                        Dispatcher.Invoke(() =>
                        {
                            var result = MessageBox.Show(string.Format("{0} Open in browser instead?", message), "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                            if (result == MessageBoxResult.Yes)
                            {
                                Process.Start(link);
                            }
                        });
                    }
                    Dispatcher.Invoke(() =>
                    {
                        mainWindow.ScanSongs();
                        if (!downloadFailed)
                        {
                            mainWindow.StatusLabel.Content = "Download complete.";
                        }
                    });
                });
            };
            ContextMenu = contextMenu;
        }
Example #7
0
        public static SongDownloader GetDefaultDownloader()
        {
            var hasher = new SongHasher(TestSongsDir, Path.Combine(TestCacheDir, "TestSongsHashData.dat"));

            var history = new HistoryManager(Path.Combine(HistoryTestPathDir, "TestSongsHistory.json"));

            history.Initialize();
            var downloader = new SongDownloader(BeatSync.Configs.PluginConfig.DefaultConfig, history, hasher, TestSongsDir);

            return(downloader);
        }
        public void SongDoesExist()
        {
            var historyManager = new HistoryManager(DefaultHistoryPath);
            var songHasher     = new SongHasher(DefaultSongsPath, DefaultHashCachePath);

            historyManager.Initialize();
            var downloader = new SongDownloader(defaultConfig, historyManager, songHasher, DefaultSongsPath);
            var exists     = new PlaylistSong("d375405d047d6a2a4dd0f4d40d8da77554f1f677", "Does Exist", "5e20", "ejiejidayo");

            historyManager.TryAdd(exists, 0); // Song is added before it gets to DownloadJob
            var result = downloader.DownloadJob(exists).Result;

            Assert.AreEqual(exists.Hash, result.HashAfterDownload);
            Assert.IsTrue(historyManager.ContainsKey(exists.Hash)); // Successful download is kept in history
        }
        protected void didSelectLevel(IDifficultyBeatmap difficultyBeatmap)
        {
            IBeatmapLevel level = difficultyBeatmap.level;

            Logger.Debug($"select level {level.songName} - {difficultyBeatmap.difficulty} - {difficultyBeatmap.difficultyRank}");
            if (!_partyFlowCoordinator || !_partyFlowCoordinator.isActivated)
            {
                toggleButtons(true);
                return;
            }
            toggleButtons(false);
            SteamAPI.SetSong(level.levelID, level.songName);
            SteamAPI.SetDifficulty((byte)difficultyBeatmap.difficultyRank);
            SongDownloader.Instance.StartCoroutine(SongDownloader.CheckSongExists(level.levelID, doesSongExist));
        }
Example #10
0
        public SongListItem(GameplayParameters parameters)
        {
            this.parameters   = parameters;
            cancellationToken = new CancellationTokenSource();

            if (OstHelper.IsOst(parameters.Beatmap.LevelId) || SongUtils.masterLevelList.Any(x => x.levelID == parameters.Beatmap.LevelId))
            {
                downloadState = DownloadState.Complete;
                level         = SongUtils.masterLevelList.First(x => x.levelID == parameters.Beatmap.LevelId);
            }
            else
            {
                SongDownloader.DownloadSong(parameters.Beatmap.LevelId, true, OnSongDownloaded, OnDownloadProgress);
            }
        }
Example #11
0
        public void Start()
        {
            Logger.log?.Debug("BeatSync Start()");
            IsRunning = true;
            var recentPlaylist = Plugin.config.Value.RecentPlaylistDays > 0 ? PlaylistManager.GetPlaylist(BuiltInPlaylist.BeatSyncRecent) : null;

            if (recentPlaylist != null && Plugin.config.Value.RecentPlaylistDays > 0)
            {
                var minDate      = DateTime.Now - new TimeSpan(Plugin.config.Value.RecentPlaylistDays, 0, 0, 0);
                int removedCount = recentPlaylist.Songs.RemoveAll(s => s.DateAdded < minDate);

                if (removedCount > 0)
                {
                    if (!recentPlaylist.TryWriteFile(out Exception ex))
                    {
                        Logger.log.Warn($"Unable to write {recentPlaylist.FileName}: {ex.Message}");
                        Logger.log.Debug(ex);
                    }
                    else
                    {
                        Logger.log?.Info($"Removed {removedCount} old songs from the RecentPlaylist.");
                    }
                }
                else
                {
                    Logger.log?.Info("Didn't remove any songs from RecentPlaylist.");
                }
            }
            var syncInterval = new TimeSpan(Plugin.config.Value.TimeBetweenSyncs.Hours, Plugin.config.Value.TimeBetweenSyncs.Minutes, 0);
            var nowTime      = DateTime.Now;

            if (Plugin.config.Value.LastRun + syncInterval <= nowTime)
            {
                if (Plugin.config.Value.LastRun != DateTime.MinValue)
                {
                    Logger.log.Info($"BeatSync ran {TimeSpanToString(nowTime - Plugin.config.Value.LastRun)} ago");
                }
                SongHasher     = new SongHasher(Plugin.CustomLevelsPath, Plugin.CachedHashDataPath);
                HistoryManager = new HistoryManager(Path.Combine(Plugin.UserDataPath, "BeatSyncHistory.json"));
                Task.Run(() => HistoryManager.Initialize());
                Downloader = new SongDownloader(Plugin.config.Value, HistoryManager, SongHasher, CustomLevelPathHelper.customLevelsDirectoryPath);
                StartCoroutine(HashSongsCoroutine());
            }
            else
            {
                Logger.log.Info($"BeatSync ran {TimeSpanToString(nowTime - Plugin.config.Value.LastRun)} ago, skipping because TimeBetweenSyncs is {Plugin.config.Value.TimeBetweenSyncs}");
            }
        }
        public void SongDoesntExist()
        {
            //Assert.AreEqual(1, SongFeedReaders.WebUtils.WebClient.Timeout);
            //var response = SongFeedReaders.WebUtils.WebClient.GetAsync(@"http://releases.ubuntu.com/18.04.3/ubuntu-18.04.3-live-server-amd64.iso").Result;
            //var dResult = response.Content.ReadAsFileAsync("ubuntu.iso", true).Result;
            var historyManager = new HistoryManager(DefaultHistoryPath);
            var songHasher     = new SongHasher(DefaultSongsPath, DefaultHashCachePath);

            historyManager.Initialize();
            var downloader  = new SongDownloader(defaultConfig, historyManager, songHasher, DefaultSongsPath);
            var doesntExist = new PlaylistSong("196be1af64958d8b5375b328b0eafae2151d46f8", "Doesn't Exist", "ffff", "Who knows");

            historyManager.TryAdd(doesntExist, 0); // Song is added before it gets to DownloadJob
            var result = downloader.DownloadJob(doesntExist).Result;

            Assert.IsTrue(historyManager.ContainsKey(doesntExist.Hash)); // Keep song in history so it doesn't try to download a non-existant song again.
        }
Example #13
0
        public void SingleThreaded_FirstSongNotFound()
        {
            var songsPath = Path.Combine(DefaultSongsPath, "SingleThreaded_FirstSongNotFound");

            if (Directory.Exists(songsPath))
            {
                Directory.Delete(songsPath, true);
            }
            var downloader = new SongDownloader(defaultConfig, null, null, songsPath);
            var testSong1  = new PlaylistSong("A65C4B43A6BC543AC6B534A65CB43B6AC354", "NotFoundSong", "fff0", "MapperName");
            var testSong2  = new PlaylistSong("19f2879d11a91b51a5c090d63471c3e8d9b7aee3", "Believer", "b", "rustic");

            downloader.DownloadQueue.Enqueue(testSong1);
            downloader.DownloadQueue.Enqueue(testSong2);
            var results = downloader.RunDownloaderAsync(1).Result;

            Assert.AreEqual(2, results.Count);
            Assert.AreEqual(404, results[0].DownloadResult.HttpStatusCode);
            Assert.AreEqual(true, results[1].Successful);
        }
Example #14
0
        public void BeatSaverHot()
        {
            var config       = DefaultConfig;
            var sourceConfig = DefaultConfig.BeatSaver;

            sourceConfig.MaxConcurrentPageChecks = 5;
            var feedConfig = sourceConfig.Hot;

            feedConfig.MaxSongs = 60;
            var songDownloader = new SongDownloader(config, null, null, SONGSPATH);
            var reader         = new BeatSaverReader();
            var settings       = feedConfig.ToFeedSettings();

            CancellationTokenSource cts = new CancellationTokenSource();
            var resultTask = songDownloader.ReadFeed(reader, settings, 0, null, PlaylistStyle.Append, cts.Token);


            var result = resultTask.Result;

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count > 0);
        }
        private void _songDetailViewController_favoriteButtonPressed(Song song)
        {
            if (PluginConfig.favoriteSongs.Any(x => x.Contains(song.hash)))
            {
                PluginConfig.favoriteSongs.Remove(SongDownloader.GetLevelID(song));
                PluginConfig.SaveConfig();

                _songDetailViewController.SetFavoriteState(false);
                PlaylistsCollection.RemoveLevelFromPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), SongDownloader.GetLevelID(song));
            }
            else
            {
                PluginConfig.favoriteSongs.Add(SongDownloader.GetLevelID(song));
                PluginConfig.SaveConfig();

                _songDetailViewController.SetFavoriteState(true);
                PlaylistsCollection.AddSongToPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), new PlaylistSong()
                {
                    levelId = SongDownloader.GetLevelID(song), songName = song.songName, level = SongDownloader.GetLevel(SongDownloader.GetLevelID(song)), key = song.id
                });
            }
        }
Example #16
0
        public void BeatSaverHot_Cancelled()
        {
            var config       = DefaultConfig;
            var sourceConfig = DefaultConfig.BeatSaver;

            sourceConfig.MaxConcurrentPageChecks = 5;
            var feedConfig = sourceConfig.Hot;

            feedConfig.MaxSongs = 60;
            var songDownloader = new SongDownloader(config, null, null, SONGSPATH);
            var reader         = new BeatSaverReader();
            var settings       = feedConfig.ToFeedSettings();

            CancellationTokenSource cts = new CancellationTokenSource(150);
            var resultTask = songDownloader.ReadFeed(reader, settings, 0, null, PlaylistStyle.Append, cts.Token);


            var result = resultTask.Result;

            Assert.IsNotNull(result);
            Assert.IsFalse(result.Successful);
            Assert.AreEqual(FeedResultError.Cancelled, result.ErrorCode);
        }
Example #17
0
        public void BeastSaberBookmarks()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            var config       = DefaultConfig;
            var sourceConfig = DefaultConfig.BeastSaber;

            sourceConfig.MaxConcurrentPageChecks = 5;
            var feedConfig = sourceConfig.Bookmarks;

            feedConfig.MaxSongs = 60;
            var songDownloader = new SongDownloader(config, null, null, SONGSPATH);
            var reader         = new BeastSaberReader(sourceConfig.Username, sourceConfig.MaxConcurrentPageChecks);
            var settings       = feedConfig.ToFeedSettings();

            var result = songDownloader.ReadFeed(reader, settings, 0, null, PlaylistStyle.Append, cts.Token).Result;

            if (!result.Successful)
            {
                Console.WriteLine(result.FaultedResults.First().Exception);
            }
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count > 0);
        }
        public static void LoadAvatar()
        {
            if (defaultAvatarInstance == null)
            {
                if (Config.Instance.DownloadAvatars)
                {
                    defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault(x => x.FullPath.ToLower().Contains("loading.avatar"));

                    if (defaultAvatarInstance == null)//fallback to multiplayer avatar
                    {
                        defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault(x => x.FullPath.ToLower().Contains("multiplayer.avatar"));
                    }

                    if (defaultAvatarInstance == null)//fallback to default avatar
                    {
                        defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault(x => x.FullPath.ToLower().Contains("templatefullbody.avatar"));
                    }

                    if (defaultAvatarInstance == null)//fallback to ANY avatar
                    {
                        defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault();
                    }
                }
                else
                {
                    defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault(x => x.FullPath.ToLower().Contains("multiplayer.avatar"));

                    if (defaultAvatarInstance == null)//fallback to default avatar
                    {
                        defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault(x => x.FullPath.ToLower().Contains("templatefullbody.avatar"));
                    }

                    if (defaultAvatarInstance == null)//fallback to ANY avatar
                    {
                        defaultAvatarInstance = CustomAvatar.Plugin.Instance.AvatarLoader.Avatars.FirstOrDefault();
                    }
                }
            }
#if DEBUG
            Misc.Logger.Info($"Found avatar, isLoaded={defaultAvatarInstance.IsLoaded}");
#endif
            if (!defaultAvatarInstance.IsLoaded)
            {
                defaultAvatarInstance.Load(null);
            }

            foreach (CustomAvatar.CustomAvatar avatar in CustomAvatar.Plugin.Instance.AvatarLoader.Avatars)
            {
                Task.Run(() =>
                {
                    string hash;
                    if (SongDownloader.CreateMD5FromFile(avatar.FullPath, out hash))
                    {
                        ModelSaberAPI.cachedAvatars.Add(hash, avatar);
#if DEBUG
                        Misc.Logger.Info("Hashed avatar " + avatar.Name + "! Hash: " + hash);
#endif
                    }
                }).ConfigureAwait(false);
            }
        }
Example #19
0
        private void SetupTweaks()
        {
            _mainFlowCoordinator = FindObjectOfType <MainFlowCoordinator>();
            _mainFlowCoordinator.GetPrivateField <MainMenuViewController>("_mainMenuViewController").didFinishEvent += SongListTweaks_didFinishEvent;

            RectTransform viewControllersContainer = FindObjectsOfType <RectTransform>().First(x => x.name == "ViewControllers");

            if (initialized || PluginConfig.disableSongListTweaks)
            {
                return;
            }

            Logger.Log("Setting up song list tweaks...");

            try
            {
                var harmony = HarmonyInstance.Create("BeatSaverDownloaderHarmonyInstance");
                harmony.PatchAll(Assembly.GetExecutingAssembly());
            }
            catch (Exception e)
            {
                Logger.Log("Unable to patch level list! Exception: " + e);
            }

            _playlistsFlowCoordinator = new GameObject("PlaylistsFlowCoordinator").AddComponent <PlaylistsFlowCoordinator>();
            _playlistsFlowCoordinator.didFinishEvent += _playlistsFlowCoordinator_didFinishEvent;

            if (SongLoader.AreSongsLoaded)
            {
                _levelCollection = SongLoader.CustomLevelCollectionSO;
            }
            else
            {
                SongLoader.SongsLoadedEvent += (SongLoader sender, List <CustomLevel> levels) =>
                {
                    _levelCollection = SongLoader.CustomLevelCollectionSO;
                };
            }

            _simpleDialog = ReflectionUtil.GetPrivateField <SimpleDialogPromptViewController>(_mainFlowCoordinator, "_simpleDialogPromptViewController");
            _simpleDialog = Instantiate(_simpleDialog.gameObject, _simpleDialog.transform.parent).GetComponent <SimpleDialogPromptViewController>();

            _levelListViewController = viewControllersContainer.GetComponentInChildren <LevelPackLevelsViewController>(true);
            _levelListViewController.didSelectLevelEvent += _levelListViewController_didSelectLevelEvent;

            _levelPacksViewController = viewControllersContainer.GetComponentInChildren <LevelPacksViewController>(true);
            _levelPacksViewController.didSelectPackEvent += _levelPacksViewController_didSelectPackEvent;

            TableView     _songSelectionTableView = _levelListViewController.GetComponentsInChildren <TableView>(true).First();
            RectTransform _tableViewRectTransform = _levelListViewController.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "LevelsTableView");

            _tableViewRectTransform.sizeDelta        = new Vector2(0f, -20.5f);
            _tableViewRectTransform.anchoredPosition = new Vector2(0f, -2.5f);

            Button _pageUp = _tableViewRectTransform.GetComponentsInChildren <Button>(true).First(x => x.name == "PageUpButton");

            (_pageUp.transform as RectTransform).anchoredPosition = new Vector2(0f, -1f);

            Button _pageDown = _tableViewRectTransform.GetComponentsInChildren <Button>(true).First(x => x.name == "PageDownButton");

            (_pageDown.transform as RectTransform).anchoredPosition = new Vector2(0f, 1f);

            _fastPageUpButton = Instantiate(_pageUp, _tableViewRectTransform, false);
            (_fastPageUpButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 1f);
            (_fastPageUpButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 1f);
            (_fastPageUpButton.transform as RectTransform).anchoredPosition = new Vector2(-26f, 1f);
            (_fastPageUpButton.transform as RectTransform).sizeDelta        = new Vector2(8f, 6f);
            _fastPageUpButton.GetComponentsInChildren <RectTransform>().First(x => x.name == "BG").sizeDelta        = new Vector2(8f, 6f);
            _fastPageUpButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Arrow").sprite = Sprites.DoubleArrow;
            _fastPageUpButton.onClick.AddListener(delegate()
            {
                FastScrollUp(_songSelectionTableView, PluginConfig.fastScrollSpeed);
            });

            _fastPageDownButton = Instantiate(_pageDown, _tableViewRectTransform, false);
            (_fastPageDownButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0f);
            (_fastPageDownButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0f);
            (_fastPageDownButton.transform as RectTransform).anchoredPosition = new Vector2(-26f, -1f);
            (_fastPageDownButton.transform as RectTransform).sizeDelta        = new Vector2(8f, 6f);
            _fastPageDownButton.GetComponentsInChildren <RectTransform>().First(x => x.name == "BG").sizeDelta        = new Vector2(8f, 6f);
            _fastPageDownButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Arrow").sprite = Sprites.DoubleArrow;
            _fastPageDownButton.onClick.AddListener(delegate()
            {
                FastScrollDown(_songSelectionTableView, PluginConfig.fastScrollSpeed);
            });

            _randomButton         = Instantiate(viewControllersContainer.GetComponentsInChildren <Button>(true).First(x => x.name == "PracticeButton"), _levelListViewController.rectTransform, false);
            _randomButton.onClick = new Button.ButtonClickedEvent();
            _randomButton.onClick.AddListener(() =>
            {
                int randomRow = UnityEngine.Random.Range(0, _songSelectionTableView.dataSource.NumberOfCells());
                _songSelectionTableView.ScrollToCellWithIdx(randomRow, TableView.ScrollPositionType.Beginning, false);
                _songSelectionTableView.SelectCellWithIdx(randomRow, true);
            });
            _randomButton.name = "CustomUIButton";

            (_randomButton.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0.5f);
            (_randomButton.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0.5f);
            (_randomButton.transform as RectTransform).anchoredPosition = new Vector2(35f, 36.25f);
            (_randomButton.transform as RectTransform).sizeDelta        = new Vector2(8.8f, 6f);

            _randomButton.SetButtonText("");
            _randomButton.SetButtonIcon(Sprites.RandomIcon);
            _randomButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Stroke").sprite = Resources.FindObjectsOfTypeAll <Sprite>().First(x => x.name == "RoundRectSmallStroke");

            var _randomIconLayout = _randomButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _randomIconLayout.padding = new RectOffset(0, 0, 0, 0);

            _searchButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), SearchPressed, "Search");
            _searchButton.SetButtonTextSize(3f);
            _searchButton.ToggleWordWrapping(false);

            _sortByButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.SortBy);
            }, "Sort By");
            _sortByButton.SetButtonTextSize(3f);
            _sortByButton.ToggleWordWrapping(false);

            _playlistsButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), PlaylistsButtonPressed, "Playlists");
            _playlistsButton.SetButtonTextSize(3f);
            _playlistsButton.ToggleWordWrapping(false);

            _defButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(SortMode.Default, "");
            },
                                                                 "Default");

            _defButton.SetButtonTextSize(3f);
            _defButton.ToggleWordWrapping(false);
            _defButton.gameObject.SetActive(false);

            _newButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(SortMode.Newest, "");
            }, "Newest");

            _newButton.SetButtonTextSize(3f);
            _newButton.ToggleWordWrapping(false);
            _newButton.gameObject.SetActive(false);


            _difficultyButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(SortMode.Difficulty, "");
            }, "Difficulty");

            _difficultyButton.SetButtonTextSize(3f);
            _difficultyButton.ToggleWordWrapping(false);
            _difficultyButton.gameObject.SetActive(false);

            _detailViewController = viewControllersContainer.GetComponentsInChildren <StandardLevelDetailViewController>(true).First(x => x.name == "LevelDetailViewController");
            _detailViewController.didChangeDifficultyBeatmapEvent += _difficultyViewController_didSelectDifficultyEvent;

            RectTransform buttonsRect = _detailViewController.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "PlayButtons");

            _favoriteButton         = Instantiate(viewControllersContainer.GetComponentsInChildren <Button>(true).First(x => x.name == "PracticeButton"), buttonsRect, false);
            _favoriteButton.onClick = new Button.ButtonClickedEvent();
            _favoriteButton.onClick.AddListener(() =>
            {
                if (PluginConfig.favoriteSongs.Any(x => x.Contains(_detailViewController.selectedDifficultyBeatmap.level.levelID)))
                {
                    PluginConfig.favoriteSongs.Remove(_detailViewController.selectedDifficultyBeatmap.level.levelID);
                    PluginConfig.SaveConfig();
                    _favoriteButton.SetButtonIcon(Sprites.AddToFavorites);
                    PlaylistsCollection.RemoveLevelFromPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), _detailViewController.selectedDifficultyBeatmap.level.levelID);
                }
                else
                {
                    PluginConfig.favoriteSongs.Add(_detailViewController.selectedDifficultyBeatmap.level.levelID);
                    PluginConfig.SaveConfig();
                    _favoriteButton.SetButtonIcon(Sprites.RemoveFromFavorites);
                    PlaylistsCollection.AddSongToPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), new PlaylistSong()
                    {
                        levelId = _detailViewController.selectedDifficultyBeatmap.level.levelID, songName = _detailViewController.selectedDifficultyBeatmap.level.songName, level = SongDownloader.GetLevel(_detailViewController.selectedDifficultyBeatmap.level.levelID)
                    });
                }
            });
            _favoriteButton.name = "CustomUIButton";
            _favoriteButton.SetButtonIcon(Sprites.AddToFavorites);
            (_favoriteButton.transform as RectTransform).sizeDelta = new Vector2(12f, 8.8f);
            var _favoriteIconLayout = _favoriteButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _favoriteIconLayout.padding = new RectOffset(3, 3, 0, 0);
            _favoriteButton.transform.SetAsFirstSibling();

            Button practiceButton = buttonsRect.GetComponentsInChildren <Button>().First(x => x.name == "PracticeButton");

            (practiceButton.transform as RectTransform).sizeDelta = new Vector2(12f, 8.8f);
            var _practiceIconLayout = practiceButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _practiceIconLayout.padding = new RectOffset(3, 3, 0, 0);

            _deleteButton         = Instantiate(viewControllersContainer.GetComponentsInChildren <Button>(true).First(x => x.name == "PracticeButton"), buttonsRect, false);
            _deleteButton.onClick = new Button.ButtonClickedEvent();
            _deleteButton.onClick.AddListener(DeletePressed);
            _deleteButton.name = "CustomUIButton";
            _deleteButton.SetButtonIcon(Sprites.DeleteIcon);
            _deleteButton.interactable = !PluginConfig.disableDeleteButton;
            (_deleteButton.transform as RectTransform).sizeDelta = new Vector2(8.8f, 8.8f);
            _deleteButton.GetComponentsInChildren <UnityEngine.UI.Image>().First(x => x.name == "Stroke").sprite = Resources.FindObjectsOfTypeAll <Sprite>().First(x => x.name == "RoundRectSmallStroke");

            var _deleteIconLayout = _deleteButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content");

            _deleteIconLayout.padding = new RectOffset(0, 0, 1, 1);

            _deleteButton.transform.SetAsLastSibling();

            //based on https://github.com/halsafar/BeatSaberSongBrowser/blob/master/SongBrowserPlugin/UI/Browser/SongBrowserUI.cs#L192
            var statsPanel     = _detailViewController.GetComponentsInChildren <LevelParamsPanel>(true).First(x => x.name == "LevelParamsPanel");
            var statTransforms = statsPanel.GetComponentsInChildren <RectTransform>(true);
            var valueTexts     = statsPanel.GetComponentsInChildren <TextMeshProUGUI>(true).Where(x => x.name == "ValueText").ToList();

            foreach (RectTransform r in statTransforms)
            {
                if (r.name == "Separator")
                {
                    continue;
                }
                r.sizeDelta = new Vector2(r.sizeDelta.x * 0.85f, r.sizeDelta.y * 0.85f);
            }

            var _starStatTransform = Instantiate(statTransforms[1], statsPanel.transform, false);

            _starStatText = _starStatTransform.GetComponentInChildren <TextMeshProUGUI>(true);
            _starStatTransform.GetComponentInChildren <UnityEngine.UI.Image>(true).sprite = Sprites.StarFull;
            _starStatText.text = "--";

            ResultsViewController _standardLevelResultsViewController = viewControllersContainer.GetComponentsInChildren <ResultsViewController>(true).First(x => x.name == "StandardLevelResultsViewController");

            _standardLevelResultsViewController.continueButtonPressedEvent += _standardLevelResultsViewController_continueButtonPressedEvent;

            initialized = true;
        }
Example #20
0
        public async void Start()
        {
            Plugin.log?.Debug("BeatSync Start()");
            IsRunning = true;
            SetupComponents();

            if (playlistManager != null)
            {
                var recentPlaylist = Plugin.config.RecentPlaylistDays > 0 ? playlistManager.GetOrAddPlaylist(BuiltInPlaylist.BeatSyncRecent) : null;
                if (recentPlaylist != null && Plugin.config.RecentPlaylistDays > 0)
                {
                    var minDate      = DateTime.Now - new TimeSpan(Plugin.config.RecentPlaylistDays, 0, 0, 0);
                    int removedCount = recentPlaylist.RemoveAll(s => s.DateAdded < minDate);
                    if (removedCount > 0)
                    {
                        Plugin.log?.Info($"Removed {removedCount} old songs from the RecentPlaylist.");
                        recentPlaylist.RaisePlaylistChanged();
                        try
                        {
                            playlistManager.StorePlaylist(recentPlaylist);
                        }
                        catch (Exception ex)
                        {
                            Plugin.log?.Warn($"Unable to write {recentPlaylist.Filename}: {ex.Message}");
                            Plugin.log?.Debug(ex);
                        }
                    }
                    else
                    {
                        Plugin.log?.Info("Didn't remove any songs from RecentPlaylist.");
                    }
                }
            }
            var syncInterval = new TimeSpan(Plugin.modConfig.TimeBetweenSyncs.Hours, Plugin.modConfig.TimeBetweenSyncs.Minutes, 0);
            var nowTime      = DateTime.Now;

            if (Plugin.config.LastRun + syncInterval <= nowTime)
            {
                if (Plugin.config.LastRun != DateTime.MinValue)
                {
                    Plugin.log?.Info($"BeatSync ran {TimeSpanToString(nowTime - Plugin.config.LastRun)} ago");
                }
                if (songHasher != null)
                {
                    await songHasher.InitializeAsync().ConfigureAwait(false);

                    Plugin.log?.Info($"Hashed {songHasher.HashDictionary.Count} songs in {CustomLevelsDirectory}.");
                }
                else
                {
                    Plugin.log?.Error($"SongHasher was null.");
                }
                // Start downloader
                IJobBuilder    jobBuilder     = CreateJobBuilder(Plugin.config);
                SongDownloader songDownloader = new SongDownloader();
                JobManager     JobManager     = new JobManager(Plugin.config.MaxConcurrentDownloads);
                JobManager.Start(CancelAllToken);
                Stopwatch sw = new Stopwatch();
                sw.Start();
                if (jobBuilder.SongTargets.Count() == 0)
                {
                    Plugin.log?.Error("jobBuilder has no SongTargets.");
                }
                JobStats[] sourceStats = await songDownloader.RunAsync(Plugin.config, jobBuilder, JobManager).ConfigureAwait(false); // TODO: CancellationToken

                JobStats beatSyncStats = sourceStats.Aggregate((a, b) => a + b);
                await JobManager.CompleteAsync();

                int      recentPlaylistDays = Plugin.config.RecentPlaylistDays;
                DateTime cutoff             = DateTime.Now - new TimeSpan(recentPlaylistDays, 0, 0, 0);
                foreach (SongTarget target in jobBuilder.SongTargets)
                {
                    if (target is ITargetWithPlaylists targetWithPlaylists)
                    {
                        PlaylistManager?targetPlaylistManager = targetWithPlaylists.PlaylistManager;
                        if (recentPlaylistDays > 0)
                        {
                            BeatSaberPlaylistsLib.Types.IPlaylist?recent = targetPlaylistManager?.GetOrAddPlaylist(BuiltInPlaylist.BeatSyncRecent);
                            if (recent != null && recent.Count > 0)
                            {
                                int songsRemoved = recent.RemoveAll(s => s.DateAdded < cutoff);
                                if (songsRemoved > 0)
                                {
                                    recent.RaisePlaylistChanged();
                                }
                            }
                        }
                        try
                        {
                            targetPlaylistManager?.StoreAllPlaylists();
                        }
                        catch (AggregateException ex)
                        {
                            Plugin.log?.Error($"Error storing playlists: {ex.Message}");
                            foreach (var e in ex.InnerExceptions)
                            {
                                Plugin.log?.Debug(e);
                            }
                        }
                        catch (Exception ex)
                        {
                            Plugin.log?.Error($"Error storing playlists: {ex.Message}");
                            Plugin.log?.Debug(ex);
                        }
                    }
                    if (target is ITargetWithHistory targetWithHistory)
                    {
                        try
                        {
                            targetWithHistory.HistoryManager?.WriteToFile();
                        }
                        catch (Exception ex)
                        {
                            Plugin.log?.Info($"Unable to save history at '{targetWithHistory.HistoryManager?.HistoryPath}': {ex.Message}");
                        }
                    }
                }
                sw.Stop();
                Plugin.log?.Info($"Finished after {sw.Elapsed.TotalSeconds}s: {beatSyncStats}");
                Plugin.config.LastRun = DateTime.Now;
                Plugin.ConfigManager.SaveConfig();
                SongCore.Loader loader = SongCore.Loader.Instance;
                SongCore.Loader.SongsLoadedEvent -= Loader_SongsLoadedEvent;
                SongCore.Loader.SongsLoadedEvent += Loader_SongsLoadedEvent;
                if (!SongCore.Loader.AreSongsLoading)
                {
                    SongCore.Loader.SongsLoadedEvent -= Loader_SongsLoadedEvent;
                    if (SongCore.Loader.AreSongsLoaded)
                    {
                        loader.RefreshSongs();
                    }
                }
            }
            else
            {
                Plugin.log?.Info($"BeatSync ran {TimeSpanToString(nowTime - Plugin.config.LastRun)} ago, skipping because TimeBetweenSyncs is {Plugin.modConfig.TimeBetweenSyncs}");
            }
        }
Example #21
0
        static async Task Main(string[] args)
        {
            try
            {
                ConsoleLogWriter?consoleLogger = SetupLogging();
                string           version       = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0.0";
                Logger.log.Info($"Starting BeatSyncConsole v{version}");
                await CheckVersion().ConfigureAwait(false);

                ConfigManager = new ConfigManager(ConfigDirectory);
                bool validConfig = await ConfigManager.InitializeConfigAsync().ConfigureAwait(false);

                if (consoleLogger != null)
                {
                    consoleLogger.LogLevel = ConfigManager.Config?.ConsoleLogLevel ?? BeatSyncLib.Logging.LogLevel.Info;
                }
                Config?config = ConfigManager.Config;
                if (validConfig && config != null && config.BeatSyncConfig != null)
                {
                    SongFeedReaders.WebUtils.Initialize(new WebUtilities.HttpClientWrapper.HttpClientWrapper());
                    SongFeedReaders.WebUtils.WebClient.SetUserAgent("BeatSyncConsole/" + version);
                    JobManager manager = new JobManager(config.BeatSyncConfig.MaxConcurrentDownloads);
                    manager.Start(CancellationToken.None);
                    IJobBuilder jobBuilder = await CreateJobBuilderAsync(config).ConfigureAwait(false);

                    SongDownloader songDownloader = new SongDownloader();
                    Stopwatch      sw             = new Stopwatch();
                    sw.Start();
                    JobStats[] sourceStats = await songDownloader.RunAsync(config.BeatSyncConfig, jobBuilder, manager).ConfigureAwait(false);

                    JobStats beatSyncStats = sourceStats.Aggregate((a, b) => a + b);
                    await manager.CompleteAsync().ConfigureAwait(false);

                    int      recentPlaylistDays = config.BeatSyncConfig.RecentPlaylistDays;
                    DateTime cutoff             = DateTime.Now - new TimeSpan(recentPlaylistDays, 0, 0, 0);
                    foreach (SongTarget?target in jobBuilder.SongTargets)
                    {
                        if (target is ITargetWithPlaylists targetWithPlaylists)
                        {
                            PlaylistManager?targetPlaylistManager = targetWithPlaylists.PlaylistManager;
                            if (recentPlaylistDays > 0)
                            {
                                IPlaylist?recent = targetPlaylistManager?.GetOrAddPlaylist(BuiltInPlaylist.BeatSyncRecent);
                                if (recent != null && recent.Count > 0)
                                {
                                    int songsRemoved = recent.RemoveAll(s => s.DateAdded < cutoff);
                                    if (songsRemoved > 0)
                                    {
                                        recent.RaisePlaylistChanged();
                                    }
                                }
                            }
                            try
                            {
                                targetPlaylistManager?.StoreAllPlaylists();
                            }
                            catch (AggregateException ex)
                            {
                                Logger.log.Error($"Error storing playlists: {ex.Message}");
                                foreach (var e in ex.InnerExceptions)
                                {
                                    Logger.log.Debug(e);
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.log.Error($"Error storing playlists: {ex.Message}");
                                Logger.log.Debug(ex);
                            }
                        }
                        if (target is ITargetWithHistory targetWithHistory)
                        {
                            try
                            {
                                targetWithHistory.HistoryManager?.WriteToFile();
                            }
                            catch (Exception ex)
                            {
                                Logger.log.Info($"Unable to save history at '{targetWithHistory.HistoryManager?.HistoryPath}': {ex.Message}");
                            }
                        }
                    }
                    sw.Stop();
                    Logger.log.Info($"Finished after {sw.Elapsed.TotalSeconds}s: {beatSyncStats}");
                    config.BeatSyncConfig.LastRun = DateTime.Now;
                }
                else
                {
                    Logger.log.Info("BeatSyncConsole cannot run without a valid config, exiting.");
                }

                LogManager.Stop();
                LogManager.Wait();
                Console.WriteLine("Press Enter to continue...");
                Console.Read();
            }
            catch (Exception ex)
            {
                string message = $"Fatal Error in BeatSyncConsole: {ex.Message}\n{ex.StackTrace}";
                if (LogManager.IsAlive && LogManager.HasWriters && Logger.log != null)
                {
                    Logger.log.Error(message);
                }
                else
                {
                    ConsoleColor previousColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(message);
                    Console.ForegroundColor = previousColor;
                }

                LogManager.Stop();
                LogManager.Wait();
                Console.WriteLine("Press Enter to continue...");
                Console.Read();
            }
            finally
            {
                LogManager.Abort();
            }
        }
Example #22
0
        private void btnStartDownLoad_Click(object sender, EventArgs e)
        {
            try
            {
                tsState.Value   = 0;
                tsState.Visible = true;

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (downloader == null)
                {
                    downloader = new SongDownloader(provider, path);
                }

                foreach (ListViewItem item in lvSongs.CheckedItems)
                {
                    timer1.Enabled  = true;
                    timer1.Interval = 100;
                    MergedSong1 song = (MergedSong1)item.Tag;
                    downloader.AddDownload(song);

                    //若路径更改,则不往库中保存数据
                    if (txtDownLoadPath.Text.Trim() == Directory.GetCurrentDirectory() + @"\misucs\")
                    {
                        //判断歌手是否已存在,若不存在则添加
                        if (!isExeitsSinger(song.Singer))
                        {
                            KtvMSModel.Singer singer = new KtvMSModel.Singer();
                            singer.Name = song.Singer;
                            singerManager.AddSingerInfo(singer);
                        }

                        //根据歌名判断歌曲是否存在,
                        if (!newSongManager.isExeitsSongByName(song.SongName))
                        {
                            Song1 song1 = new Song1();
                            song1.SongName = song.SongName;
                            song1.Singer   = song.Singer;
                            song1.Source   = song.Source;
                            song1.Duration = song.Duration;                                                //播放时间
                            song1.Size     = Convert.ToDouble((song.Size / (1024 * 1024)).ToString("F2")); //歌曲文件大小


                            int row = newSongManager.AddSong(song1);//添加歌曲
                            if (row > 0)
                            {
                                int songId = newSongManager.GetSongIdByName(song.SongName);
                                if (songId != null && songId != 0)
                                {
                                    downloadSongManger.AddDownloadSong(songId);//下载记录
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 private async Task DownloadSongAsync(Song testSong, bool overrideExisting = true)
 {
     SongDownloader downloader = new SongDownloader(SongDownloadPath, overrideExisting);
     await downloader.DownloadAsync(testSong);
 }
Example #24
0
        private void SetupTweaks()
        {
            if (initialized || PluginConfig.disableSongListTweaks)
            {
                return;
            }

            Logger.Log("Setting up song list tweaks...");

            _playlistsFlowCoordinator = (new GameObject("PlaylistsFlowCoordinator")).AddComponent <PlaylistsFlowCoordinator>();
            _playlistsFlowCoordinator.didFinishEvent += _playlistsFlowCoordinator_didFinishEvent;

            _beatmapCharacteristics = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>();
            _lastCharacteristic     = _beatmapCharacteristics.First(x => x.characteristicName == "Standard");

            Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSelectionViewController>().First().didSelectBeatmapCharacteristicEvent += (BeatmapCharacteristicSelectionViewController sender, BeatmapCharacteristicSO selected) => { _lastCharacteristic = selected; };

            if (SongLoader.AreSongsLoaded)
            {
                _levelCollection = SongLoader.CustomLevelCollectionSO;
            }
            else
            {
                SongLoader.SongsLoadedEvent += (SongLoader sender, List <CustomLevel> levels) => {
                    _levelCollection = SongLoader.CustomLevelCollectionSO;
                };
            }

            _mainFlowCoordinator = Resources.FindObjectsOfTypeAll <MainFlowCoordinator>().FirstOrDefault();
            _mainFlowCoordinator.GetPrivateField <MainMenuViewController>("_mainMenuViewController").didFinishEvent += SongListTweaks_didFinishEvent;

            _simpleDialog = ReflectionUtil.GetPrivateField <SimpleDialogPromptViewController>(_mainFlowCoordinator, "_simpleDialogPromptViewController");
            _simpleDialog = Instantiate(_simpleDialog.gameObject, _simpleDialog.transform.parent).GetComponent <SimpleDialogPromptViewController>();

            _difficultyViewController = Resources.FindObjectsOfTypeAll <BeatmapDifficultyViewController>().FirstOrDefault();
            _difficultyViewController.didSelectDifficultyEvent += _difficultyViewController_didSelectDifficultyEvent;

            _levelListViewController = Resources.FindObjectsOfTypeAll <LevelListViewController>().FirstOrDefault();
            _levelListViewController.didSelectLevelEvent += _levelListViewController_didSelectLevelEvent;;

            RectTransform _tableViewRectTransform = _levelListViewController.GetComponentsInChildren <RectTransform>().First(x => x.name == "TableViewContainer");

            _tableViewRectTransform.sizeDelta        = new Vector2(0f, -20f);
            _tableViewRectTransform.anchoredPosition = new Vector2(0f, -2.5f);

            RectTransform _pageUp = _tableViewRectTransform.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "PageUpButton");

            _pageUp.anchoredPosition = new Vector2(0f, -1f);

            RectTransform _pageDown = _tableViewRectTransform.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "PageDownButton");

            _pageDown.anchoredPosition = new Vector2(0f, 1f);

            _searchButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), SearchPressed, "Search");
            _searchButton.SetButtonTextSize(3f);
            _searchButton.ToggleWordWrapping(false);

            _sortByButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.SortBy);
            }, "Sort By");
            _sortByButton.SetButtonTextSize(3f);
            _sortByButton.ToggleWordWrapping(false);

            _playlistsButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), PlaylistsButtonPressed, "Playlists");
            _playlistsButton.SetButtonTextSize(3f);
            _playlistsButton.ToggleWordWrapping(false);

            _defButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(_lastCharacteristic, SortMode.Default, "");
            },
                                                                 "Default");

            _defButton.SetButtonTextSize(3f);
            _defButton.ToggleWordWrapping(false);
            _defButton.gameObject.SetActive(false);

            _newButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(_lastCharacteristic, SortMode.Newest, "");
            }, "Newest");

            _newButton.SetButtonTextSize(3f);
            _newButton.ToggleWordWrapping(false);
            _newButton.gameObject.SetActive(false);


            _authorButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () =>
            {
                SelectTopButtons(TopButtonsState.Select);
                SetLevels(_lastCharacteristic, SortMode.Difficulty, "");
            }, "Difficulty");

            _authorButton.SetButtonTextSize(3f);
            _authorButton.ToggleWordWrapping(false);
            _authorButton.gameObject.SetActive(false);

            _detailViewController = Resources.FindObjectsOfTypeAll <StandardLevelDetailViewController>().First(x => x.name == "StandardLevelDetailViewController");
            RectTransform buttonsRect = _detailViewController.GetComponentsInChildren <RectTransform>().First(x => x.name == "Buttons");

            buttonsRect.anchoredPosition = new Vector2(0f, 10.75f);

            RectTransform customButtonsRect = Instantiate(buttonsRect, buttonsRect.parent, true);

            Destroy(customButtonsRect.GetComponent <ContentSizeFitter>());
            Destroy(customButtonsRect.GetComponent <HorizontalLayoutGroup>());

            customButtonsRect.name             = "CustomUIButtonsHolder";
            customButtonsRect.anchoredPosition = new Vector2(0f, 1.25f);

            _favoriteButton = customButtonsRect.GetComponentsInChildren <Button>().First(x => x.name == "PracticeButton");
            _favoriteButton.SetButtonIcon(Base64Sprites.AddToFavorites);
            _favoriteButton.onClick.AddListener(() => {
                if (PluginConfig.favoriteSongs.Any(x => x.Contains(_detailViewController.difficultyBeatmap.level.levelID)))
                {
                    PluginConfig.favoriteSongs.Remove(_detailViewController.difficultyBeatmap.level.levelID);
                    PluginConfig.SaveConfig();
                    _favoriteButton.SetButtonIcon(Base64Sprites.AddToFavorites);
                    PlaylistsCollection.RemoveLevelFromPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), _detailViewController.difficultyBeatmap.level.levelID);
                }
                else
                {
                    PluginConfig.favoriteSongs.Add(_detailViewController.difficultyBeatmap.level.levelID);
                    PluginConfig.SaveConfig();
                    _favoriteButton.SetButtonIcon(Base64Sprites.RemoveFromFavorites);
                    PlaylistsCollection.AddSongToPlaylist(PlaylistsCollection.loadedPlaylists.First(x => x.playlistTitle == "Your favorite songs"), new PlaylistSong()
                    {
                        levelId = _detailViewController.difficultyBeatmap.level.levelID, songName = _detailViewController.difficultyBeatmap.level.songName, level = SongDownloader.GetLevel(_detailViewController.difficultyBeatmap.level.levelID)
                    });
                }
            });

            _deleteButton = customButtonsRect.GetComponentsInChildren <Button>().First(x => x.name == "PlayButton");
            _deleteButton.SetButtonText("Delete");
            _deleteButton.ToggleWordWrapping(false);
            _deleteButton.onClick.AddListener(DeletePressed);
            _deleteButton.GetComponentsInChildren <RectTransform>().First(x => x.name == "GlowContainer").gameObject.SetActive(false);
            _deleteButton.interactable = !PluginConfig.disableDeleteButton;

            //based on https://github.com/halsafar/BeatSaberSongBrowser/blob/master/SongBrowserPlugin/UI/Browser/SongBrowserUI.cs#L192
            var statsPanel     = _detailViewController.GetComponentsInChildren <CanvasRenderer>(true).First(x => x.name == "LevelParamsPanel");
            var statTransforms = statsPanel.GetComponentsInChildren <RectTransform>();
            var valueTexts     = statsPanel.GetComponentsInChildren <TextMeshProUGUI>().Where(x => x.name == "ValueText").ToList();

            foreach (RectTransform r in statTransforms)
            {
                if (r.name == "Separator")
                {
                    continue;
                }
                r.sizeDelta = new Vector2(r.sizeDelta.x * 0.85f, r.sizeDelta.y * 0.85f);
            }

            var _starStatTransform = Instantiate(statTransforms[1], statsPanel.transform, false);

            _starStatText = _starStatTransform.GetComponentInChildren <TextMeshProUGUI>();
            _starStatTransform.GetComponentInChildren <UnityEngine.UI.Image>().sprite = Base64Sprites.StarFull;
            _starStatText.text = "--";

            initialized = true;
        }
Example #25
0
 public void OnPointerClick(PointerEventData eventData)
 {
     SongDownloader.DownloadAudicaFile(downloadUrl);
     transform.DOShakeScale(2f, 0.02f, 0, 2, true);
     background.DOFade(0.7f, 0.5f);
 }