Exemple #1
0
        public static async Task <bool> TryRenewOsuCookies()
        {
            try // try renew
            {
                System.Net.CookieContainer _cookies = await Osu.LoginAndGetCookie(SettingManager.Get("officialOsuUsername"), SettingManager.Get("officialOsuPassword"));

                Properties.Settings.Default.officialOsuCookies = await Osu.SerializeCookies(_cookies);

                Osu.Cookies = _cookies;
                Properties.Settings.Default.Save(); // success
                return(true);
            }
            catch (Osu.InvalidPasswordException)
            {
                MessageBoxResult fallback = MessageBox.Show("It seems like your osu! login password has changed. Press yes to fallback the session to Bloodcat for now and you can go update your password, or press no to permanently use Bloodcat. You will have to retry the download again either way.", "NexDirect - Download Error", MessageBoxButton.YesNo, MessageBoxImage.Error);
                if (fallback == MessageBoxResult.Yes)
                {
                    // just fallback
                    SettingManager.Set("useOfficialOsu", false, true);
                    SettingManager.Set("fallbackActualOsu", true, true);
                    return(false);
                }
                else
                {
                    // disable perma
                    SettingManager.Set("useOfficialOsu", false);
                    SettingManager.Set("officialOsuCookies", null);
                    SettingManager.Set("officialOsuUsername", "");
                    SettingManager.Set("officialOsuPassword", "");
                    return(false);
                }
            }
        }
Exemple #2
0
        private async void dataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (!SettingManager.Get("audioPreviews"))
            {
                return;
            }

            var set = WinTools.GetGridViewSelectedRowItem <BeatmapSet>(sender, e);

            if (set == null)
            {
                return;
            }

            if (set == lastSetPreviewed)
            {
                forceStopPreview();
                lastSetPreviewed = null;
                return;
            }

            // hacky
            forceStopPreview(); // if already playing something just stop it
            await Task.Delay(250);

            // kind of a hack, pt 2
            if (DownloadManager.Downloads.Any(d => d.Set.Id == set.Id))
            {
                return; // check for if already d/l'ing overlaps
            }
            previewPlayer = await Osu.PlayPreviewAudio(set, (float)SettingManager.Get("previewVolume"));

            lastSetPreviewed = set;
        }
Exemple #3
0
        /// <summary>
        ///     Goes through all the mapsets in the queue and imports them.
        /// </summary>
        public static void ImportMapsetsInQueue()
        {
            Map selectedMap = null;

            if (MapManager.Selected.Value != null)
            {
                selectedMap = MapManager.Selected.Value;
            }

            for (var i = 0; i < Queue.Count; i++)
            {
                var file             = Queue[i];
                var time             = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Milliseconds;
                var extractDirectory = $@"{ConfigManager.SongDirectory}/{Path.GetFileNameWithoutExtension(file)} - {time}/";
                ImportingMapset.Invoke(typeof(MapsetImporter), new ImportingMapsetEventArgs(Queue, Path.GetFileName(file), i));

                try
                {
                    if (file.EndsWith(".qp"))
                    {
                        ExtractQuaverMapset(file, extractDirectory);
                        File.Delete(file);
                    }
                    else if (file.EndsWith(".osz"))
                    {
                        Osu.ConvertOsz(file, extractDirectory);
                        File.Delete(file);
                    }
                    else if (file.EndsWith(".sm"))
                    {
                        Stepmania.ConvertFile(file, extractDirectory);
                    }

                    selectedMap = InsertAndUpdateSelectedMap(extractDirectory);

                    Logger.Important($"Successfully imported {file}", LogType.Runtime);
                }
                catch (Exception e)
                {
                    Logger.Error(e, LogType.Runtime);
                    NotificationManager.Show(NotificationLevel.Error, $"Failed to import file: {Path.GetFileName(file)}");
                }
            }

            MapDatabaseCache.OrderAndSetMapsets();

            var mapset = MapManager.Mapsets.Find(x => x.Maps.Any(y => y.Md5Checksum == selectedMap?.Md5Checksum));

            if (mapset == null)
            {
                mapset = MapManager.Mapsets.First();
                MapManager.Selected.Value = mapset.Maps.First();
            }
            else
            {
                MapManager.Selected.Value = mapset.Maps.Find(x => x.Md5Checksum == selectedMap?.Md5Checksum);
            }

            Queue.Clear();
        }
Exemple #4
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hash = 17;
         hash = hash * 23 + Osu?.GetHashCode() ?? 1;
         hash = hash * 23 + Taiko?.GetHashCode() ?? 2;
         hash = hash * 23 + Ctb?.GetHashCode() ?? 3;
         hash = hash * 23 + Mania?.GetHashCode() ?? 4;
         return(hash);
     }
 }
Exemple #5
0
        private async void search(bool newSearch)
        {
            try
            {
                searchingLoading.Visibility = Visibility.Visible;

                string        searchText = lastSearchText = newSearch ? searchBox.Text : lastSearchText;
                OsuRankStatus rankedVal  = lastRankedVal = newSearch ? (rankedStatusBox.SelectedItem as KVItem <OsuRankStatus>).Value : lastRankedVal;
                OsuModes      modeVal    = lastModeVal = newSearch ? (modeSelectBox.SelectedItem as KVItem <OsuModes>).Value : lastModeVal;

                BloodcatIdFilter?viaVal  = null;
                bool             osuMode = SettingManager.Get("useOfficialOsu");
                if (!osuMode)
                {
                    viaVal = lastBloodcatNumbersFilterVal = newSearch ? (searchViaSelectBox.Visibility == Visibility.Hidden ? null : (BloodcatIdFilter?)(searchViaSelectBox.SelectedItem as KVItem <BloodcatIdFilter>).Value) : lastBloodcatNumbersFilterVal;
                }

                searchCurrentPage = newSearch ? 1 : (searchCurrentPage + 1);

                SearchResultSet results;
                if (osuMode)
                {
                    results = await Osu.Search(searchText, rankedVal, modeVal, searchCurrentPage);
                }
                else
                {
                    results = await Bloodcat.Search(searchText, rankedVal, modeVal, viaVal, searchCurrentPage);
                }

                lastSearchResults = results;

                populateBeatmaps(results.Results, newSearch);
            }
            catch (Osu.SearchNotSupportedException) { MessageBox.Show("Sorry, this mode of Ranking search is currently not supported via the official osu! servers."); }
            catch (Osu.CookiesExpiredException)
            {
                if (await DownloadManagement.TryRenewOsuCookies())
                {
                    search(newSearch); // success, try at it again
                }
                return;
            }
            catch (Exception ex) { MessageBox.Show("There was an error searching for beatmaps...\n\n" + ex.ToString()); }
            finally { searchingLoading.Visibility = Visibility.Hidden; }
        }
Exemple #6
0
        public static async Task TestCookies()
        {
            System.Net.CookieContainer cookies = null;
            try
            {
                cookies = await CookieStoreSerializer.DeserializeCookies(SettingManager.Get("officialOsuCookies"));
            }
            catch
            {
                // Corrupted cookie store, deleting corruption
                SettingManager.Set("officialOsuCookies", null);
                cookies = new System.Net.CookieContainer();
            }

            try
            {
                await Osu.CheckPassedLoginCookieElseUseNew(cookies, SettingManager.Get("officialOsuUsername"), SettingManager.Get("officialOsuPassword"));

                // store to parent & just persist them incase something new changed
                SettingManager.Set("officialOsuCookies", await CookieStoreSerializer.SerializeCookies(Osu.Cookies));
                return;
            }
            catch (Osu.InvalidPasswordException)
            {
                MessageBoxResult cookiePrompt = MessageBox.Show("There was an error logging in to your account. Maybe you have changed your password, etc... to update that click NO and visit settings.\nClick YES to retry connection, click NO to fall back to Bloodcat for this session.", "NexDirect - Error", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (cookiePrompt == MessageBoxResult.Yes)
                {
                    await TestCookies();

                    return;
                }
                SettingManager.Set("useOfficialOsu", false, true);
                SettingManager.Set("fallbackActualOsu", true, true);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error connecting to osu! servers, falling back to Bloodcat for this session...\n\n" + ex.ToString());
                SettingManager.Set("useOfficialOsu", false, true);
                SettingManager.Set("fallbackActualOsu", true, true);
                return;
            }
        }
Exemple #7
0
        public static async Task <bool> DirectDownload(bool isSetId, string id)
        {
            BeatmapSet set;

            if (isSetId)
            {
                if (SettingManager.Get("useOfficialOsu"))
                {
                    set = await Osu.TryResolveSetId(id);
                }
                else
                {
                    set = await Bloodcat.TryResolveSetId(id);
                }
            }
            else
            {
                if (SettingManager.Get("useOfficialOsu"))
                {
                    set = await Osu.TryResolveBeatmapId(id);
                }
                else
                {
                    set = await Bloodcat.TryBeatmapId(id);
                }
            }


            if (set == null)
            {
                MessageBox.Show($"Could not find the beatmap on {(SettingManager.Get("useOfficialOsu") ? "the official osu! directory" : "Bloodcat")}. Cannot proceed to download :(");
                return(false);
            }
            else
            {
                (new Dialogs.DirectDownload(mw, set)).ShowDialog();
                return(true);
            }
        }
Exemple #8
0
        private async void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false; // disable no spam plz

            try
            {
                System.Net.CookieContainer _cookies = await Osu.LoginAndGetCookie(usernameBox.Text, passwordBox.Text);

                SettingManager.Set("officialOsuCookies", await Osu.SerializeCookies(_cookies));
                SettingManager.Set("useOfficialOsu", true);
                //SettingManager.Set("fallbackActualOsu", true);
                SettingManager.Set("officialOsuUsername", usernameBox.Text);
                SettingManager.Set("officialOsuPassword", passwordBox.Text);
                _s.officialLoggedInAs.Content = "Currently logged in as: " + usernameBox.Text;
                MessageBox.Show("Logged in to osu! servers and login data saved.");
                Close();
                return;
            }
            catch (Osu.InvalidPasswordException) { MessageBox.Show("You have specified an incorrect password. Please try again."); }
            catch (Exception ex) { MessageBox.Show("There was an error logging in to the osu! servers...\n\n" + ex); }

            button1.Enabled = true;
        }
        private void dataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (!SettingManager.Get("audioPreviews"))
            {
                return;
            }

            var set = WinTools.GetGridViewSelectedRowItem <BeatmapSet>(sender, e);

            if (set == null)
            {
                return;
            }

            if (set == lastSetPreviewed)
            {
                AudioManager.ForceStopPreview();
                lastSetPreviewed = null;
                return;
            }

            Osu.PlayPreviewAudio(set);
            lastSetPreviewed = set;
        }
Exemple #10
0
        public static async void DownloadBeatmapSet(BeatmapSet set)
        {
            // check for already downloading
            if (DownloadManager.Downloads.Any(b => b.Set.Id == set.Id))
            {
                MessageBox.Show("This beatmap is already being downloaded!");
                return;
            }

            if (!checkAndPromptIfHaveMap(set))
            {
                return;
            }

            // get dl obj
            BeatmapDownload download;

            if (!SettingManager.Get("fallbackActualOsu") && SettingManager.Get("useOfficialOsu") && String.IsNullOrEmpty(SettingManager.Get("beatmapMirror")))
            {
                try
                {
                    download = await Osu.PrepareDownloadSet(set, SettingManager.Get("novidDownload"));
                }
                catch (Osu.IllegalDownloadException)
                {
                    MessageBoxResult bloodcatAsk = MessageBox.Show("Sorry, this map seems like it has been taken down from the official osu! servers due to a DMCA request to them. Would you like to check if a copy off Bloodcat is available, and if so download it?", "NexDirect - Mirror?", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (bloodcatAsk == MessageBoxResult.No)
                    {
                        return;
                    }

                    BeatmapSet newSet = await Bloodcat.TryResolveSetId(set.Id);

                    if (newSet == null)
                    {
                        MessageBox.Show("Sorry, this map could not be found on Bloodcat. Download has been aborted.", "NexDirect - Could not find beatmap", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                    download = Bloodcat.PrepareDownloadSet(set, SettingManager.Get("beatmapMirror"));
                }
                catch (Osu.CookiesExpiredException)
                {
                    if (await TryRenewOsuCookies())
                    {
                        download = await Osu.PrepareDownloadSet(set, SettingManager.Get("novidDownload"));
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else
            {
                download = Bloodcat.PrepareDownloadSet(set, SettingManager.Get("beatmapMirror"));
            }

            if (download == null)
            {
                return;
            }

            // start dl
            try
            {
                await DownloadManager.DownloadSet(download);

                if (download.Cancelled)
                {
                    return;
                }

                if (SettingManager.Get("launchOsu") && Process.GetProcessesByName("osu!").Length > 0)
                {
                    string newPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, download.FileName);
                    File.Move(download.TempPath, newPath); // rename to .osz
                    Process.Start(Path.Combine(SettingManager.Get("osuFolder"), "osu!.exe"), newPath);
                }
                else
                {
                    string path = Path.Combine(mw.osuSongsFolder, download.FileName);
                    if (File.Exists(path))
                    {
                        File.Delete(path);                    // overwrite if exist
                    }
                    File.Move(download.TempPath, path);
                }

                (new Dialogs.DownloadComplete(set)).Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error has occured whilst downloading {set.Title} ({set.Mapper}).\n\n{ex.ToString()}");
            }
        }
Exemple #11
0
 private void previewBtn_Click(object sender, RoutedEventArgs e)
 => Osu.PlayPreviewAudio(set);
Exemple #12
0
        private async Task DiscordOnMessageReceived(MessageReceivedEventArgs e)
        {
            var db    = _serviceProvider.GetRequiredService <AatroxDbContext>();
            var repo  = db.RequestRepository <IGetOrAddRepository <GuildEntity> >();
            var guild = await repo.GetOrAddAsync(e.Message.Guild.Id);

            if (!guild.ResolveOsuUrls)
            {
                return;
            }

            if (!Uri.TryCreate(e.Message.Content, UriKind.Absolute, out var uri))
            {
                return;
            }

            if (uri.Host != "osu.ppy.sh")
            {
                return;
            }

            var url   = uri.AbsoluteUri;
            var split = url.Split('/', StringSplitOptions.RemoveEmptyEntries);
            var mode  = split[3].Split('#')[1];

            mode = mode switch
            {
                "fruits" => "catch",
                "osu" => "standard",
                "taiko" => "taiko",
                _ => "standard"
            };

            var beatmapId = split[4];

            var beatmap = await Osu.GetBeatmapByIdAsync(long.Parse(beatmapId),
                                                        (GameMode)Enum.Parse(typeof(GameMode), mode, true), true);

            ReadOnlyDictionary <float, PerformanceData>?pps = null;

            if (beatmap == null)
            {
                _log.Warn("Beatmap null?");
                return;
            }

            var gc         = (CachedGuildChannel)e.Message.Channel;
            var permission = gc.Guild.CurrentMember.GetPermissionsFor(gc);

            if (permission.Has(Permission.Administrator) || permission.Has(Permission.ManageMessages))
            {
                await((CachedUserMessage)e.Message).ModifyAsync(x => x.Flags = MessageFlags.SuppressedEmbeds);
            }

            try
            {
                pps = await OppaiClient.GetPPAsync(long.Parse(beatmapId), new float[] { 100, 99, 98, 97, 95 });
            }
            catch (Exception ex)
            {
                _log.Error("Attempting to get PP for a converted beatmap. It failed.", ex);
            }

            var successRate = 0.0;

            if (beatmap.PassCount.HasValue && beatmap.PlayCount.HasValue)
            {
                successRate = Math.Round((double)beatmap.PassCount.Value / beatmap.PlayCount.Value, 2) * 100;
            }

            var embed = new LocalEmbedBuilder
            {
                Color  = _config.DefaultEmbedColor,
                Author = new LocalEmbedAuthorBuilder
                {
                    Name    = $"{beatmap.Title} - {beatmap.Artist} [{beatmap.Difficulty}] | {beatmap.GameMode}",
                    Url     = uri.ToString(),
                    IconUrl = beatmap.ThumbnailUri.ToString()
                },
                Description = $"This beatmap was made by `{beatmap.Author}` (`{beatmap.AuthorId}`). It has an average BPM of `{beatmap.Bpm}`.",
                Footer      = new LocalEmbedFooterBuilder
                {
                    Text = $"{beatmap.State} since {beatmap.LastUpdate:g} | {beatmap.FavoriteCount} favs | {successRate}% success rate"
                },
                ThumbnailUrl = beatmap.ThumbnailUri.ToString()
            };

            var str = $"CS: `{beatmap.CircleSize}` | AR: `{beatmap.ApproachRate}`" +
                      $"\nOD: `{beatmap.OverallDifficulty}` | HP: `{beatmap.HpDrain}`";

            if (beatmap.MaxCombo.HasValue)
            {
                str += $"\nMax combo: `{beatmap.MaxCombo}`";
            }
            else if (pps != null)
            {
                str += $"\nMax combo: `{pps.First().Value.MaxCombo}`";
            }

            if (pps != null)
            {
                str += $"\n`{Math.Round(pps.First().Value.Stars, 2)}` stars";
            }

            embed.AddField("Difficulties", str, true);

            embed.AddField("Lengths", $"Length: `{beatmap.TotalLength:g}`" +
                           $"\nHit Length: `{beatmap.HitLength:g}`", true);

            if (pps != null)
            {
                var lines = pps.Select(x => $"`{Math.Round(x.Key)}%: {Math.Round(x.Value.Pp)}`");
                embed.AddField("Performance Points", string.Join(" | ", lines));
            }

            if (beatmap.GameMode == GameMode.Catch || beatmap.GameMode == GameMode.Mania)
            {
                embed.AddField("Not supported!",
                               $"**`{beatmap.GameMode}` is not supported. Star rating and performance points cannot be calculated.**");
            }

            await e.Message.Channel.SendMessageAsync(embed : embed.Build());

            AddOrUpdateValue(e.Message.Channel.Id, beatmap.BeatmapId);
        }
    }
Exemple #13
0
 private async void previewBtn_Click(object sender, RoutedEventArgs e)
 {
     previewPlayer = await Osu.PlayPreviewAudio(set, (float)SettingManager.Get("previewVolume"));
 }