Ejemplo n.º 1
0
        public static void InsertBeatmap(SoraDbContextFactory factory, Beatmaps bm)
        {
            using var db = factory.GetForWrite();

            if (db.Context.BeatmapSets.Count(x => x.Id == bm.BeatmapSetId) < 1)
            {
                db.Context.BeatmapSets.Add(
                    new BeatmapSets
                {
                    Id             = bm.BeatmapSetId,
                    Beatmaps       = new List <Beatmaps>(new[] { bm }),
                    FavouriteCount = 0,
                    PassCount      = 0,
                    LastUpdate     = DateTime.UtcNow,
                    PlayCount      = 0
                }
                    );
            }
            if (db.Context.Beatmaps.Count(x => x.Id == bm.Id) < 1)
            {
                db.Context.Beatmaps.Add(bm);
            }
            else
            {
                db.Context.Beatmaps.Update(bm);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Check if User has Obtained an achievement on this Score Submission
        /// </summary>
        /// <param name="factory">Context Factory</param>
        /// <param name="user">Who tries to Obtain</param>
        /// <param name="score">Submitted Score</param>
        /// <param name="map">Beatmap</param>
        /// <param name="set">Beatmap Set</param>
        /// <param name="oldLB">Old LeaderBoard</param>
        /// <param name="newLB">New LeaderBoard</param>
        /// <returns>Obtained Achievements</returns>
        public static string ProcessAchievements(SoraDbContextFactory factory,
                                                 Users user,
                                                 Scores score,
                                                 CheesegullBeatmap map,
                                                 CheesegullBeatmapSet set,
                                                 LeaderboardStd oldLB,
                                                 LeaderboardStd newLB)
        {
            var _l = new List <Achievements>();

            if ((int)newLB.PerformancePointsOsu == 4914)
            {
                var ach = Achievements.GetAchievement(factory, "oog");
                if (!user.AlreadyOptainedAchievement(ach))
                {
                    _l.Add(ach);
                }
            }

            // Insert custom achievements here. I'll implement a Plugin System later! but this will work for now.


            // END OF CUSTOM ACHIEVEMENTS

            var retVal = "";

            foreach (var ach in _l)
            {
                retVal += ach.ToOsuString() + "/";
            }
            retVal.TrimEnd('/');

            return(retVal);
        }
Ejemplo n.º 3
0
 public static Beatmaps FetchFromDatabase(SoraDbContextFactory factory, string fileMd5, int beatmapId = -1)
 {
     return(factory.Get().Beatmaps.FirstOrDefault(
                bm => bm.FileMd5 == fileMd5 ||
                bm.Id == beatmapId
                ));
 }
Ejemplo n.º 4
0
 public static IEnumerable <int> GetFriends(SoraDbContextFactory factory, int userId)
 {
     return(factory.Get()
            .Friends
            .Where(t => t.UserId == userId)
            .Select(x => x.FriendId).ToList());
 }
Ejemplo n.º 5
0
        public static Achievements NewAchievement(
            SoraDbContextFactory factory,
            string name,
            string displayName,
            string desc,
            string iconUri,
            bool insert = true)
        {
            using var db = factory.GetForWrite();

            var a = new Achievements
            {
                Name        = name,
                DisplayName = displayName,
                Description = desc,
                IconURI     = iconUri,
                BitId       = 1ul << db.Context.Achievements.Count()
            };

            if (!insert)
            {
                return(a);
            }

            db.Context.Achievements.Add(a);

            return(a);
        }
Ejemplo n.º 6
0
        // I could do that better but this looks nice :3
        public uint GetPosition(SoraDbContextFactory factory, PlayMode mode)
        {
            var pos = 0;

            switch (mode)
            {
            case PlayMode.Osu:
                pos = factory.Get().LeaderboardStd.Count(x => x.PerformancePointsOsu > PerformancePointsOsu);
                break;

            case PlayMode.Taiko:
                pos = factory.Get().LeaderboardStd.Count(x => x.PerformancePointsTaiko > PerformancePointsTaiko);
                break;

            case PlayMode.Ctb:
                pos = factory.Get().LeaderboardStd.Count(x => x.PerformancePointsCtb > PerformancePointsCtb);
                break;

            case PlayMode.Mania:
                pos = factory.Get().LeaderboardStd.Count(x => x.PerformancePointsMania > PerformancePointsMania);
                break;
            }

            return((uint)pos + 1);
        }
Ejemplo n.º 7
0
        public void IncreaseCountMiss(SoraDbContextFactory factory, int c, PlayMode mode)
        {
            using var db = factory.GetForWrite();

            switch (mode)
            {
            case PlayMode.Osu:
                CountMissOsu += c;
                break;

            case PlayMode.Taiko:
                CountMissTaiko += c;
                break;

            case PlayMode.Ctb:
                CountMissCtb += c;
                break;

            case PlayMode.Mania:
                CountMissMania += c;
                break;
            }

            db.Context.LeaderboardStd.Update(this);
        }
Ejemplo n.º 8
0
        public void IncreasePlaycount(SoraDbContextFactory factory, PlayMode mode)
        {
            using var db = factory.GetForWrite();

            switch (mode)
            {
            case PlayMode.Osu:
                PlayCountOsu++;
                break;

            case PlayMode.Taiko:
                PlayCountTaiko++;
                break;

            case PlayMode.Ctb:
                PlayCountCtb++;
                break;

            case PlayMode.Mania:
                PlayCountMania++;
                break;
            }

            db.Context.LeaderboardStd.Update(this);
        }
Ejemplo n.º 9
0
        public static void InsertScore(SoraDbContextFactory factory, Scores score)
        {
            using var db = factory.GetForWrite();

            var sc =
                db.Context.Scores
                .Where(s => s.FileMd5 == score.FileMd5 && s.PlayMode == score.PlayMode)
                .Where(
                    s => (score.Mods & Mod.Relax) != 0
                          ? (score.Mods & Mod.Relax) != 0
                          : (score.Mods & Mod.Relax) == 0
                    )
                .Where(s => s.UserId == score.UserId)
                .OrderByDescending(s => s.TotalScore)
                .ToList();

            var isBetter = sc.Any(scr => scr.TotalScore < score.TotalScore);

            if (isBetter)
            {
                db.Context.RemoveRange(sc);
            }

            db.Context.Add(score);
        }
Ejemplo n.º 10
0
        public static Scores GetScore(SoraDbContextFactory factory, int scoreId)
        {
            var s = factory.Get().Scores.First(score => score.Id == scoreId);

            s.ScoreOwner = Users.GetUser(factory, s.UserId);
            return(s);
        }
Ejemplo n.º 11
0
        public static void AddFriend(SoraDbContextFactory factory, int userId, int friendId)
        {
            using var db = factory.GetForWrite();

            db.Context.Friends.Add(new Friends {
                UserId = userId, FriendId = friendId
            });
        }
Ejemplo n.º 12
0
 public AchievementController(
     SoraDbContextFactory factory,
     Cache cache
     )
 {
     _factory = factory;
     _cache   = cache;
 }
Ejemplo n.º 13
0
        public static IEnumerable <Scores> GetScores(
            SoraDbContextFactory factory,
            string fileMd5, Users user, PlayMode playMode = PlayMode.Osu,
            bool relaxing    = false,
            bool friendsOnly = false, bool countryOnly = false, bool modOnly = false,
            Mod mods         = Mod.None, bool onlySelf = false)
        {
            CountryIds cid = 0;

            if (countryOnly)
            {
                cid = UserStats.GetUserStats(factory, user.Id).CountryId;
            }

            var query = factory.Get().Scores
                        .Where(score => score.FileMd5 == fileMd5 && score.PlayMode == playMode)
                        .Where(
                score
                => relaxing
                                           ? (score.Mods & Mod.Relax) != 0
                                           : (score.Mods & Mod.Relax) == 0
                )
                        .Where(
                score
                => !friendsOnly || factory.Get().Friends
                .Where(f => f.UserId == user.Id)
                .Select(f => f.FriendId)
                .Contains(score.UserId)
                )
                        .Where(
                score
                => !countryOnly || factory.Get().UserStats
                .Select(c => c.CountryId)
                .Contains(cid)
                )
                        .Where(score => !modOnly || score.Mods == mods)
                        .Where(score => !onlySelf || score.UserId == user.Id)
                        .OrderByDescending(score => score.TotalScore)
                        .GroupBy(s => s.UserId)
                        .Take(50);

            IEnumerable <Scores> result = query.ToArray().Select(s => s.Select(xs => xs).First()).ToList();

            foreach (var s in result)
            {
                s.Position = factory.Get().Scores
                             .Where(score => score.FileMd5 == fileMd5 && score.PlayMode == playMode)
                             .Where(
                    score
                    => relaxing
                                                ? (score.Mods & Mod.Relax) != 0
                                                : (score.Mods & Mod.Relax) == 0
                    )
                             .OrderByDescending(score => score.TotalScore)
                             .IndexOf(s) + 1;
            }
            return(result);
        }
Ejemplo n.º 14
0
        public static BeatmapSets GetBeatmapSet(SoraDbContextFactory factory, int setId)
        {
            var sts = factory.Get().BeatmapSets.FirstOrDefault(s => s.Id == setId);

            if (sts != null)
            {
                sts.Beatmaps = factory.Get().Beatmaps.Where(s => s.BeatmapSetId == sts.Id).ToList();
            }

            return(sts);
        }
Ejemplo n.º 15
0
        public void IncreaseScore(SoraDbContextFactory factory, ulong score, bool ranked, PlayMode mode)
        {
            using var db = factory.GetForWrite();

            switch (mode)
            {
            case PlayMode.Osu:
                if (ranked)
                {
                    RankedScoreOsu += score;
                }
                else
                {
                    TotalScoreOsu += score;
                }
                break;

            case PlayMode.Taiko:
                if (ranked)
                {
                    RankedScoreTaiko += score;
                }
                else
                {
                    TotalScoreTaiko += score;
                }
                break;

            case PlayMode.Ctb:
                if (ranked)
                {
                    RankedScoreCtb += score;
                }
                else
                {
                    TotalScoreCtb += score;
                }
                break;

            case PlayMode.Mania:
                if (ranked)
                {
                    RankedScoreMania += score;
                }
                else
                {
                    TotalScoreMania += score;
                }
                break;
            }

            db.Context.LeaderboardStd.Update(this);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Create Default Achievements
 /// </summary>
 /// <param name="factory">Context Factory</param>
 public static void CreateDefaultAchievements(SoraDbContextFactory factory)
 {
     if (factory.Get().Achievements.FirstOrDefault(x => x.Name == "oog") == null)
     {
         Achievements.NewAchievement(
             factory,
             "oog",
             "Oooooooooooooooog!",
             "You just oooged JSE",
             "https://onii-chan-please.come-inside.me/achivement_oog.png"
             );
     }
 }
Ejemplo n.º 17
0
 public OnLoginRequestEvent(SoraDbContextFactory factory,
                            Config cfg,
                            PresenceService pcs,
                            PacketStreamService ps,
                            ChannelService cs,
                            Cache cache)
 {
     _factory = factory;
     _cfg     = cfg;
     _pcs     = pcs;
     _ps      = ps;
     _cs      = cs;
     _cache   = cache;
 }
Ejemplo n.º 18
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore();
            services.AddMemoryCache();

            var c = new MemoryCache(new MemoryCacheOptions {
                ExpirationScanFrequency = TimeSpan.FromDays(365)
            });
            var cfgUtil = new ConfigUtil(c);

            var scfg = cfgUtil.ReadConfig <Config>();

            var f = new SoraDbContextFactory();

            f.Get().Migrate();

            services.AddSingleton(scfg)
            .AddSingleton <IConfig>(scfg)
            .AddSingleton <IMySQLConfig>(scfg)
            .AddSingleton <ICheesegullConfig>(scfg)
            .AddSingleton <IServerConfig>(scfg)
            .AddSingleton <ConfigUtil>()
            .AddSingleton <SoraDbContextFactory>()
            .AddSingleton <PluginService>()
            .AddSingleton <PresenceService>()
            .AddSingleton <MultiplayerService>()
            .AddSingleton <PacketStreamService>()
            .AddSingleton <Cache>()
            .AddSingleton <ConsoleCommandService>()
            .AddSingleton <ChannelService>()
            .AddSingleton <Bot.Sora>()
            .AddSingleton <PerformancePointsProcessor>()
            .AddSingleton(new EventManager(new List <Assembly> {
                Assembly.GetEntryAssembly()
            }));

            services.Configure <FormOptions>(
                x =>
            {
                x.ValueLengthLimit             = int.MaxValue;
                x.MultipartBodyLengthLimit     = int.MaxValue;
                x.MemoryBufferThreshold        = int.MaxValue;
                x.BufferBodyLengthLimit        = int.MaxValue;
                x.MultipartBoundaryLengthLimit = int.MaxValue;
                x.MultipartHeadersLengthLimit  = int.MaxValue;
            }
                );
        }
Ejemplo n.º 19
0
 public WebController(SoraDbContextFactory factory,
                      EventManager ev,
                      Cache cache,
                      Config config,
                      Bot.Sora sora,
                      PerformancePointsProcessor pointsProcessor,
                      PresenceService ps)
 {
     _factory         = factory;
     _ev              = ev;
     _cache           = cache;
     _config          = config;
     _sora            = sora;
     _pointsProcessor = pointsProcessor;
     _ps              = ps;
 }
Ejemplo n.º 20
0
        // ReSharper disable once MemberCanBePrivate.Global
        public static UserStats GetUserStats(SoraDbContextFactory factory, int userId)
        {
            using var db = factory.GetForWrite();

            var val = db.Context.UserStats.Where(t => t.Id == userId).Select(e => e).FirstOrDefault();

            if (val != null)
            {
                return(val);
            }

            db.Context.UserStats.Add(val = new UserStats {
                Id = userId, CountryId = 0
            });
            return(val);
        }
Ejemplo n.º 21
0
 public Scoreboard(SoraDbContextFactory factory, Config cfg,
                   string fileMd5, Users user,
                   PlayMode playMode = PlayMode.Osu, bool relaxing = false,
                   bool friendsOnly  = false, bool countryOnly     = false, bool modOnly = false,
                   Mod mods          = Mod.None)
 {
     _factory     = factory;
     _cfg         = cfg;
     _fileMd5     = fileMd5;
     _user        = user;
     _playMode    = playMode;
     _relaxing    = relaxing;
     _friendsOnly = friendsOnly;
     _countryOnly = countryOnly;
     _modOnly     = modOnly;
     _mods        = mods;
 }
Ejemplo n.º 22
0
        public static LeaderboardRx GetLeaderboard(SoraDbContextFactory factory, int userId)
        {
            using var db = factory.GetForWrite();

            var result = db.Context.LeaderboardRx.Where(t => t.Id == userId).Select(e => e).FirstOrDefault();

            if (result != null)
            {
                return(result);
            }

            db.Context.LeaderboardRx.Add(new LeaderboardRx {
                Id = userId
            });

            return(new LeaderboardRx {
                Id = userId
            });
        }
Ejemplo n.º 23
0
        public void IncreaseCount50(SoraDbContextFactory factory, int c, PlayMode mode)
        {
            using var db = factory.GetForWrite();

            switch (mode)
            {
            case PlayMode.Osu:
                Count50Osu += c;
                break;

            case PlayMode.Taiko:
                Count50Taiko += c;
                break;

            case PlayMode.Ctb:
                Count50Ctb += c;
                break;
            }

            db.Context.LeaderboardRx.Update(this);
        }
Ejemplo n.º 24
0
        public static (bool Pass, Scores score) ParseScore(SoraDbContextFactory factory, string encScore, string iv,
                                                           string osuVersion)
        {
            var decryptedScore = Crypto.DecryptString(
                Convert.FromBase64String(encScore),
                Encoding.ASCII.GetBytes(string.Format(PrivateKey, osuVersion)),
                Convert.FromBase64String(iv)
                );

            var x     = decryptedScore.Split(":");
            var score = new Scores
            {
                FileMd5    = x[0],
                UserId     = Users.GetUserId(factory, x[1]),
                Count300   = int.Parse(x[3]),
                Count100   = int.Parse(x[4]),
                Count50    = int.Parse(x[5]),
                CountGeki  = int.Parse(x[6]),
                CountKatu  = int.Parse(x[7]),
                CountMiss  = int.Parse(x[8]),
                TotalScore = int.Parse(x[9]),
                MaxCombo   = short.Parse(x[10]),
                Mods       = (Mod)uint.Parse(x[13]),
                PlayMode   = (PlayMode)byte.Parse(x[15]),
                Date       = DateTime.UtcNow
            };

            score.Accuracy = Accuracy.GetAccuracy(
                score.Count300, score.Count100, score.Count50, score.CountMiss,
                score.CountGeki, score.CountKatu, score.PlayMode
                );
            score.ScoreMd5 = Hex.ToHex(
                Crypto.GetMd5(
                    $"{score.Count300 + score.Count100}{score.FileMd5}{score.CountMiss}{score.CountGeki}{score.CountKatu}{score.Date}{score.Mods}"
                    )
                );
            score.ScoreOwner = Users.GetUser(factory, score.UserId);

            return(bool.Parse(x[14]), score);
        }
Ejemplo n.º 25
0
        public void UpdatePP(SoraDbContextFactory factory, PlayMode mode)
        {
            using var db = factory.GetForWrite();

            var TotalPP = db.Context.Scores
                          .Where(s => (s.Mods & Mod.Relax) == 0)
                          .Where(s => s.PlayMode == mode)
                          .Where(s => s.UserId == Id)
                          .OrderByDescending(s => s.PeppyPoints)
                          .Take(100).ToList()
                          .Select((t, i) => t.PeppyPoints * Math.Pow(0.95d, i))
                          .Sum();

            switch (mode)
            {
            case PlayMode.Osu:
                PerformancePointsOsu = TotalPP;
                break;

            case PlayMode.Taiko:
                PerformancePointsTaiko = TotalPP;
                break;

            case PlayMode.Ctb:
                PerformancePointsCtb = TotalPP;
                break;

            case PlayMode.Mania:
                PerformancePointsMania = TotalPP;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }

            db.Context.LeaderboardStd.Update(this);
        }
Ejemplo n.º 26
0
        public string ToOsuString(SoraDbContextFactory factory)
        {
            if (ScoreOwner == null)
            {
                ScoreOwner = Users.GetUser(factory, UserId);
            }

            return($"{Id}|" +
                   $"{ScoreOwner.Username.Replace("|", "I")}|" +
                   $"{TotalScore}|" +
                   $"{MaxCombo}|" +
                   $"{Count50}|" +
                   $"{Count100}|" +
                   $"{Count300}|" +
                   $"{CountMiss}|" +
                   $"{CountGeki}|" +
                   $"{CountKatu}|" +
                   $"{CountMiss > 0}|" +
                   $"{(short) Mods}|" +
                   $"{UserId}|" +
                   $"{Position}|" +
                   $"{(int) Date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds}|" +
                   $"{Convert.ToInt32(ReplayMd5 != string.Empty)}");
        }
Ejemplo n.º 27
0
        public Sora(SoraDbContextFactory factory,
                    IServiceProvider provider,
                    PacketStreamService pss,
                    MultiplayerService ms,
                    PresenceService ps,
                    ChannelService cs,
                    EventManager ev
                    )
        {
            _provider = provider;
            _factory  = factory;
            _pss      = pss;
            _ms       = ms;
            _ps       = ps;
            _cs       = cs;
            _ev       = ev;

            #region DEFAULT COMMANDS

            RegisterCommandClass <RestrictCommand>();
            RegisterCommandClass <DebugCommand>();

            #endregion
        }
Ejemplo n.º 28
0
 // ReSharper disable once UnusedMember.Global
 public static UserStats GetUserStats(SoraDbContextFactory factory, Users user)
 => GetUserStats(factory, user.Id);
Ejemplo n.º 29
0
        public void Configure(IApplicationBuilder app,
                              IServiceProvider provider,
                              SoraDbContextFactory factory,
                              Config config,
                              IConfig icfg,
                              PluginService plugs,
                              EventManager ev,
                              IHostingEnvironment env,
                              MultiplayerService mps,
                              PacketStreamService pss,
                              ChannelService cs,
                              PresenceService ps,
                              ConsoleCommandService ccs,
                              Bot.Sora s
                              )
        {
            app.UseMiddleware <LoggingMiddleware>();

            Logger.Info(
                @"%#FFFFFF%Sora V1.0.0

%#800000%=============================== %#F94848%License %#800000%=================================
%#F94848%Sora - A Modular Bancho written in C#
Copyright (C) 2019 Robin A. P.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
%#800000%==========================================================================

"
                );
            var w = new Stopwatch();

            Logger.Info("Generating %#F94848%Database%#FFFFFF%! this could take a while.");
            w.Start();
            // Create Sora (bot) if not exists.
            if (Users.GetUser(factory, 100) == null)
            {
                Users.InsertUser(
                    factory, new Users
                {
                    Id          = 100,
                    Username    = "******",
                    Email       = "*****@*****.**",
                    Password    = "",
                    Permissions = Permission.From(Permission.GROUP_ADMIN)
                }
                    );
            }
            w.Stop();
            Logger.Info("Done, it took%#3cfc59%", w.ElapsedMilliseconds + "ms");

            AchievementProcessor.CreateDefaultAchievements(factory);
            Localisation.Initialize();

            ev.SetProvider(provider);

            if (Environment.GetEnvironmentVariable("COS_READONLY") == null)
            {
                ccs.Start();
            }
            s.RunAsync();

            if (!Directory.Exists("plugins"))
            {
                Directory.CreateDirectory("plugins");
            }

            foreach (var plug in Directory.GetFiles("plugins"))
            {
                plugs.LoadPlugin(Directory.GetCurrentDirectory() + "/" + plug);
            }

            ev.RegisterEvents();

            ps.TimeoutCheck();

            if (!Directory.Exists("data"))
            {
                Directory.CreateDirectory("data");
            }

            app.UseDeveloperExceptionPage();

            app.UseMvc(
                routes =>
            {
                routes.MapRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}"
                    );
            }
                );
        }
Ejemplo n.º 30
0
 public OnPrivateMessageEvent(SoraDbContextFactory factory, PresenceService ps, ChannelService cs)
 {
     _factory = factory;
     _ps      = ps;
 }