Ejemplo n.º 1
0
        private void SongTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            noteTimer.Stop();
            noteTimer.Elapsed -= SongTimer_Elapsed;
            noteTimer.Dispose();
            noteTimer = null;

            songTimer.Stop();
            songTimer.Elapsed -= SongTimer_Elapsed;
            songTimer.Dispose();
            songTimer = null;

            currentlyPlayingMap  = null;
            currentlyPlayingSong = null;
            currentMaxScore      = 0;

            Logger.Debug($"SENDING RESULTS: {(Self as Player).Score}");

            var songFinished = new SongFinished();

            songFinished.Type    = SongFinished.CompletionType.Passed;
            songFinished.User    = Self as Player;
            songFinished.Beatmap = currentlyPlayingMap;
            songFinished.Score   = (Self as Player).Score;
            Send(new Packet(songFinished));

            (Self as Player).PlayState = Player.PlayStates.Waiting;
            var playerUpdated = new Event();

            playerUpdated.Type          = Event.EventType.PlayerUpdated;
            playerUpdated.ChangedObject = Self;
            Send(new Packet(playerUpdated));
        }
Ejemplo n.º 2
0
        private void MockClient_PlaySong(Beatmap map)
        {
            if (OstHelper.IsOst(map.LevelId))
            {
                return;
            }

            var match = State.Matches.First(x => x.Players.Contains(Self));

            otherPlayersInMatch = match.Players.Select(x => x.Id).Union(new Guid[] { match.Leader.Id }).ToArray();

            currentlyPlayingMap  = map;
            currentlyPlayingSong = new DownloadedSong(HashFromLevelId(map.LevelId));
            currentMaxScore      = currentlyPlayingSong.GetMaxScore(currentlyPlayingMap.Characteristic.SerializedName, currentlyPlayingMap.Difficulty);

            /*using (var libVLC = new LibVLC())
             * {
             *  var media = new Media(libVLC, currentlyPlayingSong.GetAudioPath(), FromType.FromPath);
             *  await media.Parse();
             *
             *  songTimer = new Timer();
             *  songTimer.AutoReset = false;
             *  songTimer.Interval = media.Duration;
             *  songTimer.Elapsed += SongTimer_Elapsed;
             *
             *  noteTimer = new Timer();
             *  noteTimer.AutoReset = false;
             *  noteTimer.Interval = 500;
             *  noteTimer.Elapsed += NoteTimer_Elapsed;
             *
             *  noteTimer.Start();
             *  songTimer.Start();
             * }*/

            songTimer           = new Timer();
            songTimer.AutoReset = false;
            songTimer.Interval  = 60 * 3 * 1000;
            songTimer.Elapsed  += SongTimer_Elapsed;

            noteTimer           = new Timer();
            noteTimer.AutoReset = false;
            noteTimer.Interval  = 500;
            noteTimer.Elapsed  += NoteTimer_Elapsed;

            noteTimer.Start();
            songTimer.Start();

            (Self as Player).PlayState = Player.PlayStates.InGame;
            var playerUpdated = new Event();

            playerUpdated.Type          = Event.EventType.PlayerUpdated;
            playerUpdated.ChangedObject = Self;
            Send(new Packet(playerUpdated));
        }
Ejemplo n.º 3
0
        private void SongTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            noteTimer.Stop();
            noteTimer.Elapsed -= SongTimer_Elapsed;
            noteTimer.Dispose();
            noteTimer = null;

            songTimer.Stop();
            songTimer.Elapsed -= SongTimer_Elapsed;
            songTimer.Dispose();
            songTimer = null;

            currentlyPlayingMap  = null;
            currentlyPlayingSong = null;
            currentMaxScore      = 0;
            var selfPlayer = SelfObject as Player;

            Logger.Debug($"SENDING RESULTS: {selfPlayer.Score}");

            var songFinished = new SongFinished();

            songFinished.Type    = SongFinished.Types.CompletionType.Passed;
            songFinished.User    = selfPlayer;
            songFinished.Beatmap = currentlyPlayingMap;
            songFinished.Score   = selfPlayer.Score;
            Send(new Packet(songFinished));

            selfPlayer.PlayState = Player.Types.PlayStates.Waiting;
            var playerUpdated = new Event
            {
                Type          = Event.Types.EventType.PlayerUpdated,
                ChangedObject = Google.Protobuf.WellKnownTypes.Any.Pack(selfPlayer)
            };

            Send(new Packet(playerUpdated));
        }
        public async Task AddSongAsync([Remainder] string paramString = null)
        {
            if (IsAdmin())
            {
                var eventId = paramString.ParseArgs("eventId");
                var songId  = paramString.ParseArgs("song");

                if (string.IsNullOrEmpty(eventId) || string.IsNullOrEmpty(songId))
                {
                    await ReplyAsync(embed : ("Usage: `addSong -eventId \"[event id]\" -song [song link]`\n" +
                                              "To find event ids, please run `listEvents`\n" +
                                              "Optional parameters: `-difficulty [difficulty]`, `-characteristic [characteristic]` (example: `-characteristic onesaber`), `-[modifier]` (example: `-nofail`)").ErrorEmbed());

                    return;
                }

                //Parse the difficulty input, either as an int or a string
                BeatmapDifficulty difficulty = BeatmapDifficulty.ExpertPlus;

                string difficultyArg = paramString.ParseArgs("difficulty");
                if (difficultyArg != null)
                {
                    //If the enum conversion doesn't succeed, try it as an int
                    if (!Enum.TryParse(difficultyArg, true, out difficulty))
                    {
                        await ReplyAsync(embed : "Could not parse difficulty parameter".ErrorEmbed());

                        return;
                    }
                }

                string characteristic = paramString.ParseArgs("characteristic");
                characteristic = characteristic ?? "Standard";

                GameOptions   gameOptions   = GameOptions.None;
                PlayerOptions playerOptions = PlayerOptions.None;

                //Load up the GameOptions and PlayerOptions
                foreach (GameOptions o in Enum.GetValues(typeof(GameOptions)))
                {
                    if (paramString.ParseArgs(o.ToString()) == "true")
                    {
                        gameOptions = (gameOptions | o);
                    }
                }

                foreach (PlayerOptions o in Enum.GetValues(typeof(PlayerOptions)))
                {
                    if (paramString.ParseArgs(o.ToString()) == "true")
                    {
                        playerOptions = (playerOptions | o);
                    }
                }

                //Sanitize input
                if (songId.StartsWith("https://beatsaver.com/") || songId.StartsWith("https://bsaber.com/"))
                {
                    //Strip off the trailing slash if there is one
                    if (songId.EndsWith("/"))
                    {
                        songId = songId.Substring(0, songId.Length - 1);
                    }

                    //Strip off the beginning of the url to leave the id
                    songId = songId.Substring(songId.LastIndexOf("/") + 1);
                }

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

                var server = ServerService.GetServer();
                if (server == null)
                {
                    await ReplyAsync(embed : "The Server is not running, so we can't can't add songs to it".ErrorEmbed());
                }
                else
                {
                    //Get the hash for the song
                    var hash       = BeatSaverDownloader.GetHashFromID(songId);
                    var knownPairs = await HostScraper.ScrapeHosts(server.State.KnownHosts, $"{server.CoreServer.Address}:{server.CoreServer.Port}", 0);

                    var targetPair  = knownPairs.FirstOrDefault(x => x.Value.Events.Any(y => y.EventId.ToString() == eventId));
                    var targetEvent = targetPair.Value.Events.FirstOrDefault(x => x.EventId.ToString() == eventId);
                    var songPool    = targetEvent.QualifierMaps.ToList();

                    if (OstHelper.IsOst(hash))
                    {
                        if (!SongExists(songPool, hash, characteristic, (int)difficulty, (int)gameOptions, (int)playerOptions))
                        {
                            GameplayParameters parameters = new GameplayParameters
                            {
                                Beatmap = new Beatmap
                                {
                                    Name           = OstHelper.GetOstSongNameFromLevelId(hash),
                                    LevelId        = hash,
                                    Characteristic = new Characteristic
                                    {
                                        SerializedName = characteristic
                                    },
                                    Difficulty = difficulty
                                },
                                GameplayModifiers = new GameplayModifiers
                                {
                                    Options = gameOptions
                                },
                                PlayerSettings = new PlayerSpecificSettings
                                {
                                    Options = playerOptions
                                }
                            };

                            songPool.Add(parameters);
                            targetEvent.QualifierMaps = songPool.ToArray();

                            var response = await server.SendUpdateQualifierEvent(targetPair.Key, targetEvent);

                            if (response.Type == Response.ResponseType.Success)
                            {
                                await ReplyAsync(embed : ($"Added: {parameters.Beatmap.Name} ({difficulty}) ({characteristic})" +
                                                          $"{(gameOptions != GameOptions.None ? $" with game options: ({gameOptions})" : "")}" +
                                                          $"{(playerOptions != PlayerOptions.None ? $" with player options: ({playerOptions})" : "!")}").SuccessEmbed());
                            }
                            else if (response.Type == Response.ResponseType.Fail)
                            {
                                await ReplyAsync(embed : response.Message.ErrorEmbed());
                            }
                        }
                        else
                        {
                            await ReplyAsync(embed : "Song is already active in the database".ErrorEmbed());
                        }
                    }
                    else
                    {
                        BeatSaverDownloader.DownloadSong(hash, async(songPath) =>
                        {
                            if (songPath != null)
                            {
                                DownloadedSong song = new DownloadedSong(hash);
                                string songName     = song.Name;

                                if (!song.GetBeatmapDifficulties(characteristic).Contains(difficulty))
                                {
                                    BeatmapDifficulty nextBestDifficulty = song.GetClosestDifficultyPreferLower(difficulty);

                                    if (SongExists(songPool, hash, characteristic, (int)nextBestDifficulty, (int)gameOptions, (int)playerOptions))
                                    {
                                        await ReplyAsync(embed: $"{songName} doesn't have {difficulty}, and {nextBestDifficulty} is already in the event".ErrorEmbed());
                                    }
                                    else
                                    {
                                        GameplayParameters parameters = new GameplayParameters
                                        {
                                            Beatmap = new Beatmap
                                            {
                                                Name           = songName,
                                                LevelId        = $"custom_level_{hash.ToUpper()}",
                                                Characteristic = new Characteristic
                                                {
                                                    SerializedName = characteristic
                                                },
                                                Difficulty = nextBestDifficulty
                                            },
                                            GameplayModifiers = new GameplayModifiers
                                            {
                                                Options = gameOptions
                                            },
                                            PlayerSettings = new PlayerSpecificSettings
                                            {
                                                Options = playerOptions
                                            }
                                        };

                                        songPool.Add(parameters);
                                        targetEvent.QualifierMaps = songPool.ToArray();

                                        var response = await server.SendUpdateQualifierEvent(targetPair.Key, targetEvent);
                                        if (response.Type == Response.ResponseType.Success)
                                        {
                                            await ReplyAsync(embed: ($"{songName} doesn't have {difficulty}, using {nextBestDifficulty} instead.\n" +
                                                                     $"Added to the song list" +
                                                                     $"{(gameOptions != GameOptions.None ? $" with game options: ({gameOptions})" : "")}" +
                                                                     $"{(playerOptions != PlayerOptions.None ? $" with player options: ({playerOptions})" : "!")}").SuccessEmbed());
                                        }
                                        else if (response.Type == Response.ResponseType.Fail)
                                        {
                                            await ReplyAsync(embed: response.Message.ErrorEmbed());
                                        }
                                    }
                                }
                                else
                                {
                                    GameplayParameters parameters = new GameplayParameters
                                    {
                                        Beatmap = new Beatmap
                                        {
                                            Name           = songName,
                                            LevelId        = $"custom_level_{hash.ToUpper()}",
                                            Characteristic = new Characteristic
                                            {
                                                SerializedName = characteristic
                                            },
                                            Difficulty = difficulty
                                        },
                                        GameplayModifiers = new GameplayModifiers
                                        {
                                            Options = gameOptions
                                        },
                                        PlayerSettings = new PlayerSpecificSettings
                                        {
                                            Options = playerOptions
                                        }
                                    };

                                    songPool.Add(parameters);
                                    targetEvent.QualifierMaps = songPool.ToArray();

                                    var response = await server.SendUpdateQualifierEvent(targetPair.Key, targetEvent);
                                    if (response.Type == Response.ResponseType.Success)
                                    {
                                        await ReplyAsync(embed: ($"{songName} ({difficulty}) ({characteristic}) downloaded and added to song list" +
                                                                 $"{(gameOptions != GameOptions.None ? $" with game options: ({gameOptions})" : "")}" +
                                                                 $"{(playerOptions != PlayerOptions.None ? $" with player options: ({playerOptions})" : "!")}").SuccessEmbed());
                                    }
                                    else if (response.Type == Response.ResponseType.Fail)
                                    {
                                        await ReplyAsync(embed: response.Message.ErrorEmbed());
                                    }
                                }
                            }
                            else
                            {
                                await ReplyAsync(embed: "Could not download song.".ErrorEmbed());
                            }
                        });
                    }
                }
            }
            else
            {
                await ReplyAsync(embed : "You do not have sufficient permissions to use this command".ErrorEmbed());
            }
        }
Ejemplo n.º 5
0
        protected override void Client_PacketRecieved(Packet packet)
        {
            base.Client_PacketRecieved(packet);

            if (packet.Type == PacketType.PlaySong)
            {
                PlaySong playSong = packet.SpecificPacket as PlaySong;
                PlaySong?.Invoke(playSong.Beatmap);
            }
            else if (packet.Type == PacketType.Command)
            {
                Command command = packet.SpecificPacket as Command;
                if (command.CommandType == Command.CommandTypes.ReturnToMenu)
                {
                    if ((Self as Player).PlayState == Player.PlayStates.InGame)
                    {
                        ReturnToMenu?.Invoke();
                    }
                }
            }
            else if (packet.Type == PacketType.LoadSong)
            {
                LoadSong loadSong = packet.SpecificPacket as LoadSong;

                //Send updated download status
                (Self as Player).DownloadState = Player.DownloadStates.Downloading;

                var playerUpdate = new Event();
                playerUpdate.Type          = Event.EventType.PlayerUpdated;
                playerUpdate.ChangedObject = Self;
                Send(new Packet(playerUpdate));

                var hash = HashFromLevelId(loadSong.LevelId);
                BeatSaverDownloader.DownloadSongInfoThreaded(hash,
                                                             (successfulDownload) =>
                {
                    if (successfulDownload)
                    {
                        var song = new DownloadedSong(hash);

                        var mapFormattedLevelId = $"custom_level_{hash.ToUpper()}";

                        var matchMap = new PreviewBeatmapLevel()
                        {
                            LevelId = mapFormattedLevelId,
                            Name    = song.Name
                        };

                        List <Characteristic> characteristics = new List <Characteristic>();
                        foreach (var characteristic in song.Characteristics)
                        {
                            characteristics.Add(new Characteristic()
                            {
                                SerializedName = characteristic,
                                Difficulties   = song.GetBeatmapDifficulties(characteristic)
                            });
                        }
                        matchMap.Characteristics = characteristics.ToArray();

                        //Send updated download status
                        (Self as Player).DownloadState = Player.DownloadStates.Downloaded;

                        playerUpdate               = new Event();
                        playerUpdate.Type          = Event.EventType.PlayerUpdated;
                        playerUpdate.ChangedObject = Self;
                        Send(new Packet(playerUpdate));

                        LoadedSong?.Invoke(matchMap);

                        Logger.Debug($"SENT DOWNLOADED SIGNAL {(playerUpdate.ChangedObject as Player).DownloadState}");
                    }
                    else
                    {
                        //Send updated download status
                        (Self as Player).DownloadState = Player.DownloadStates.DownloadError;

                        playerUpdate               = new Event();
                        playerUpdate.Type          = Event.EventType.PlayerUpdated;
                        playerUpdate.ChangedObject = Self;
                        Send(new Packet(playerUpdate));
                    }
                }
                                                             );
            }
        }
Ejemplo n.º 6
0
        public async Task AddSongAsync(string songId, [Remainder] string paramString = null)
        {
            if (IsAdmin())
            {
                //Parse the difficulty input, either as an int or a string
                BeatmapDifficulty difficulty = BeatmapDifficulty.ExpertPlus;

                string difficultyArg = ParseArgs(paramString, "difficulty");
                if (difficultyArg != null)
                {
                    //If the enum conversion doesn't succeed, try it as an int
                    if (!Enum.TryParse(difficultyArg, true, out difficulty))
                    {
                        await ReplyAsync("Could not parse difficulty parameter.\n" +
                                         "Usage: addSong [songId] [difficulty]");

                        return;
                    }
                }

                string characteristic = ParseArgs(paramString, "characteristic");
                characteristic = characteristic ?? "Standard";

                GameOptions   gameOptions   = GameOptions.None;
                PlayerOptions playerOptions = PlayerOptions.None;

                //Load up the GameOptions and PlayerOptions
                foreach (GameOptions o in Enum.GetValues(typeof(GameOptions)))
                {
                    if (ParseArgs(paramString, o.ToString()) == "true")
                    {
                        gameOptions = (gameOptions | o);
                    }
                }

                foreach (PlayerOptions o in Enum.GetValues(typeof(PlayerOptions)))
                {
                    if (ParseArgs(paramString, o.ToString()) == "true")
                    {
                        playerOptions = (playerOptions | o);
                    }
                }

                //Sanitize input
                if (songId.StartsWith("https://beatsaver.com/") || songId.StartsWith("https://bsaber.com/"))
                {
                    //Strip off the trailing slash if there is one
                    if (songId.EndsWith("/"))
                    {
                        songId = songId.Substring(0, songId.Length - 1);
                    }

                    //Strip off the beginning of the url to leave the id
                    songId = songId.Substring(songId.LastIndexOf("/") + 1);
                }

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

                //Get the hash for the song
                var hash = BeatSaverDownloader.GetHashFromID(songId);

                if (OstHelper.IsOst(hash))
                {
                    //if (!Song.Exists(hash, parsedDifficulty, characteristicArg, true))
                    if (!SongExists(Context.Guild.Id, hash, characteristic, (int)difficulty, (int)gameOptions, (int)playerOptions))
                    {
                        Song song = new Song
                        {
                            Name              = OstHelper.GetOstSongNameFromLevelId(hash),
                            GuildId           = Context.Guild.Id,
                            LevelId           = hash,
                            Characteristic    = characteristic,
                            BeatmapDifficulty = (int)difficulty,
                            GameOptions       = (int)gameOptions,
                            PlayerOptions     = (int)playerOptions
                        };
                        await ReplyAsync($"Added: {song.Name} ({difficulty}) ({characteristic})" +
                                         $"{(gameOptions != GameOptions.None ? $" with game options: ({gameOptions.ToString()})" : "")}" +
                                         $"{(playerOptions != PlayerOptions.None ? $" with player options: ({playerOptions.ToString()})" : "!")}");
                    }
                    else
                    {
                        await ReplyAsync("Song is already active in the database");
                    }
                }
                else
                {
                    BeatSaverDownloader.DownloadSong(hash, async(songPath) =>
                    {
                        if (songPath != null)
                        {
                            DownloadedSong song = new DownloadedSong(hash);
                            string songName     = song.Name;

                            if (!song.GetBeatmapDifficulties(characteristic).Contains(difficulty))
                            {
                                BeatmapDifficulty nextBestDifficulty = song.GetClosestDifficultyPreferLower(difficulty);

                                if (SongExists(Context.Guild.Id, hash, characteristic, (int)nextBestDifficulty, (int)gameOptions, (int)playerOptions))
                                {
                                    await ReplyAsync($"{songName} doesn't have {difficulty}, and {nextBestDifficulty} is already in the database.\n" +
                                                     $"Song not added.");
                                }

                                else
                                {
                                    Song databaseSong = new Song
                                    {
                                        Name              = OstHelper.GetOstSongNameFromLevelId(hash),
                                        GuildId           = Context.Guild.Id,
                                        LevelId           = hash,
                                        Characteristic    = characteristic,
                                        BeatmapDifficulty = (int)nextBestDifficulty,
                                        GameOptions       = (int)gameOptions,
                                        PlayerOptions     = (int)playerOptions
                                    };
                                    await ReplyAsync($"{songName} doesn't have {difficulty}, using {nextBestDifficulty} instead.\n" +
                                                     $"Added to the song list" +
                                                     $"{(gameOptions != GameOptions.None ? $" with game options: ({gameOptions})" : "")}" +
                                                     $"{(playerOptions != PlayerOptions.None ? $" with player options: ({playerOptions})" : "!")}");
                                }
                            }
                            else
                            {
                                Song databaseSong = new Song
                                {
                                    Name              = OstHelper.GetOstSongNameFromLevelId(hash),
                                    GuildId           = Context.Guild.Id,
                                    LevelId           = hash,
                                    Characteristic    = characteristic,
                                    BeatmapDifficulty = (int)difficulty,
                                    GameOptions       = (int)gameOptions,
                                    PlayerOptions     = (int)playerOptions
                                };
                                await ReplyAsync($"{songName} ({difficulty}) ({characteristic}) downloaded and added to song list" +
                                                 $"{(gameOptions != GameOptions.None ? $" with game options: ({gameOptions})" : "")}" +
                                                 $"{(playerOptions != PlayerOptions.None ? $" with player options: ({playerOptions})" : "!")}");
                            }
                        }
                        else
                        {
                            await ReplyAsync("Could not download song.");
                        }
                    });
                }
            }
        }
Ejemplo n.º 7
0
        private void MockClient_PlaySong(Beatmap map)
        {
            if (OstHelper.IsOst(map.LevelId))
            {
                return;
            }

            var match = State.Matches.First(x => x.Players.Any(p => p.Id == Self.Id && p.Name == Self.Name));

            otherPlayersInMatch = match.Players.Select(x => x.Id).Union(new string[] { match.LeaderCase == Match.LeaderOneofCase.Coordinator ? match.Coordinator.Id : match.Player.Id }).Select(s => Guid.TryParse(s, out var g) ? g : Guid.Empty).ToArray();

            currentlyPlayingMap  = map;
            currentlyPlayingSong = new DownloadedSong(HashFromLevelId(map.LevelId));
            currentMaxScore      = 0;
            notesElapsed         = 0;

            /*using (var libVLC = new LibVLC())
             * {
             *  var media = new Media(libVLC, currentlyPlayingSong.GetAudioPath(), FromType.FromPath);
             *  await media.Parse();
             *
             *  songTimer = new Timer();
             *  songTimer.AutoReset = false;
             *  songTimer.Interval = media.Duration;
             *  songTimer.Elapsed += SongTimer_Elapsed;
             *
             *  noteTimer = new Timer();
             *  noteTimer.AutoReset = false;
             *  noteTimer.Interval = 500;
             *  noteTimer.Elapsed += NoteTimer_Elapsed;
             *
             *  noteTimer.Start();
             *  songTimer.Start();
             * }*/

            songTimer           = new Timer();
            songTimer.AutoReset = false;
            songTimer.Interval  = 60 * 3 * 1000;
            songTimer.Elapsed  += SongTimer_Elapsed;

            noteTimer           = new Timer();
            noteTimer.AutoReset = false;
            noteTimer.Interval  = 500;
            noteTimer.Elapsed  += NoteTimer_Elapsed;

            noteTimer.Start();
            songTimer.Start();

            var selfPlayer = SelfObject as Player;

            selfPlayer.PlayState = Player.Types.PlayStates.InGame;

            selfPlayer.Score        = 0;
            selfPlayer.Combo        = 0;
            selfPlayer.Accuracy     = 0;
            selfPlayer.SongPosition = 0;
            multiplier = 1;

            var playerUpdated = new Event
            {
                Type          = Event.Types.EventType.PlayerUpdated,
                ChangedObject = Google.Protobuf.WellKnownTypes.Any.Pack(selfPlayer)
            };

            Send(new Packet(playerUpdated));
        }