Ejemplo n.º 1
0
        private async Task <IHttpActionResult> Handle(GetPlayersFromBitsMessage message)
        {
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);
            PlayerResult  playersResult = await bitsClient.GetPlayers(websiteConfig.ClubId);

            Player[] players = DocumentSession.Query <Player, PlayerSearch>()
                               .ToArray();

            // update existing players by matching on license number
            var playersByLicense = playersResult.Data.ToDictionary(x => x.LicNbr);

            foreach (Player player in players.Where(x => x.PlayerItem != null))
            {
                if (playersByLicense.TryGetValue(player.PlayerItem.LicNbr, out PlayerItem playerItem))
                {
                    player.PlayerItem = playerItem;
                    playersByLicense.Remove(player.PlayerItem.LicNbr);
                    Log.Info($"Updating player with existing PlayerItem: {player.PlayerItem.LicNbr}");
                }
                else
                {
                    Log.Info($"Player with {player.PlayerItem.LicNbr} not found from BITS");
                }
            }

            // add missing players, i.e. what is left from first step
            // try first to match on name, update those, add the rest
            var playerNamesWithoutPlayerItem = players.Where(x => x.PlayerItem == null).ToDictionary(x => x.Name);

            foreach (PlayerItem playerItem in playersByLicense.Values)
            {
                // look for name
                string nameFromBits = $"{playerItem.FirstName} {playerItem.SurName}";
                if (playerNamesWithoutPlayerItem.TryGetValue(nameFromBits, out Player player))
                {
                    player.PlayerItem = playerItem;
                    Log.Info($"Updating player with missing PlayerItem: {nameFromBits}");
                }
                else
                {
                    // create new
                    var newPlayer = new Player(
                        $"{playerItem.FirstName} {playerItem.SurName}",
                        playerItem.Email,
                        playerItem.Inactive ? Player.Status.Inactive : Player.Status.Active,
                        playerItem.GetPersonalNumber(),
                        string.Empty,
                        new string[0])
                    {
                        PlayerItem = playerItem
                    };
                    Log.Info($"Created player {playerItem.FirstName} {playerItem.SurName}");
                    DocumentSession.Store(newPlayer);
                }
            }

            return(Ok());
        }
Ejemplo n.º 2
0
        private async Task <IHttpActionResult> Handle(RegisterMatchMessage message)
        {
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

            Player[] players =
                DocumentSession.Query <Player, PlayerSearch>()
                .ToArray()
                .Where(x => x.PlayerItem?.LicNbr != null)
                .ToArray();
            Roster pendingMatch = DocumentSession.Load <Roster>(message.RosterId);

            try
            {
                var             parser          = new BitsParser(players);
                BitsMatchResult bitsMatchResult = await bitsClient.GetBitsMatchResult(pendingMatch.BitsMatchId);

                if (bitsMatchResult.HeadInfo.MatchFinished == false)
                {
                    Log.Info($"Match {pendingMatch.BitsMatchId} not yet finished");
                    return(Ok());
                }

                if (pendingMatch.IsFourPlayer)
                {
                    Parse4Result parse4Result = parser.Parse4(bitsMatchResult, websiteConfig.ClubId);
                    if (parse4Result != null)
                    {
                        List <string> allPlayerIds = GetPlayerIds(parse4Result);
                        pendingMatch.SetPlayers(allPlayerIds);
                        ExecuteCommand(new RegisterMatch4Command(pendingMatch, parse4Result));
                    }
                }
                else
                {
                    ParseResult parseResult = parser.Parse(bitsMatchResult, websiteConfig.ClubId);
                    if (parseResult != null)
                    {
                        List <string> allPlayerIds = GetPlayerIds(parseResult);
                        pendingMatch.SetPlayers(allPlayerIds);
                        ExecuteCommand(new RegisterMatchCommand(pendingMatch, parseResult));
                    }
                }
            }
            catch (Exception e)
            {
                ErrorSignal
                .FromCurrentContext()
                .Raise(new Exception($"Unable to auto register match {pendingMatch.Id} ({pendingMatch.BitsMatchId})", e));
                Log.Warn(e);
                return(Ok(e.ToString()));
            }

            return(Ok());
        }
Ejemplo n.º 3
0
        private IHttpActionResult Handle(GetTeamNamesQuery query)
        {
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

            GetTeamNamesQuery.TeamNameAndLevel[] teamNameAndLevels = websiteConfig.TeamNamesAndLevels
                                                                     .Select(x => new GetTeamNamesQuery.TeamNameAndLevel(x.TeamName, x.Level))
                                                                     .ToArray();
            var result = new GetTeamNamesQuery.Result(teamNameAndLevels);

            return(Ok(result));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Publish website
        /// </summary>
        public virtual void PublishWebsite()
        {
            // Get paths
            var webRoot        = GetWebRoot();
            var webConfigPath  = GetWebConfigPath();
            var isCore         = false;
            var binDir         = GetBinDirectory(out isCore);
            var configJsonPath = GetConfigJsonPath();
            var outputDir      = Path.Combine(Parameters.OutputDirectory, Parameters.OutputName);

            // Copy website binaries
            if (!isCore)
            {
                // Asp.Net: copy files to output\bin, and copy Global.asax
                DirectoryUtils.CopyDirectory(
                    binDir, Path.Combine(outputDir, "bin"), Parameters.IgnorePattern);
                File.Copy(webConfigPath, Path.Combine(outputDir, "web.config"), true);
                File.Copy(Path.Combine(webRoot, "Global.asax"),
                          Path.Combine(outputDir, "Global.asax"), true);
            }
            else
            {
                // Asp.Net Core: copy files to output\, and replace launcher path in web.config
                DirectoryUtils.CopyDirectory(binDir, outputDir, Parameters.IgnorePattern);
                var webConfig = File.ReadAllText(webConfigPath);
                webConfig = webConfig.Replace("%LAUNCHER_PATH%", GetAspNetCoreLauncherPath(binDir));
                webConfig = webConfig.Replace("%LAUNCHER_ARGS%", "");
                File.WriteAllText(Path.Combine(outputDir, "web.config"), webConfig);
            }
            // Merge website configuration
            var outputConfigJsonPath = Path.Combine(outputDir, "App_Data", "config.json");
            var config = WebsiteConfig.Merge(configJsonPath, outputConfigJsonPath);

            config.PluginDirectories = new[] { "App_Data/Plugins" };
            Directory.CreateDirectory(Path.GetDirectoryName(outputConfigJsonPath));
            File.WriteAllText(outputConfigJsonPath,
                              JsonConvert.SerializeObject(config, Formatting.Indented));
            // Copy plugins
            var originalConfig   = WebsiteConfig.FromFile(configJsonPath);
            var outputPluginRoot = Path.Combine(outputDir, config.PluginDirectories[0]);

            foreach (var pluginName in config.Plugins)
            {
                var pluginDir       = FindPluginDirectory(originalConfig, pluginName);
                var outputPluginDir = Path.Combine(outputPluginRoot, pluginName);
                DirectoryUtils.CopyDirectory(pluginDir, outputPluginDir, Parameters.IgnorePattern);
            }
            // Remove src directory under plugins
            foreach (var dir in Directory.EnumerateDirectories(
                         outputPluginRoot, "src", SearchOption.AllDirectories))
            {
                Directory.Delete(dir, true);
            }
        }
Ejemplo n.º 5
0
        public ActionResult Create()
        {
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

            ViewBag.TeamNamesAndLevels = websiteConfig.TeamNamesAndLevels;
            var vm = new CreateRosterViewModel
            {
                Season = DocumentSession.LatestSeasonOrDefault(DateTime.Now.Year)
            };

            return(View(vm));
        }
    public override Task Handle(HandlerContext <Command> context)
    {
        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

        Roster[] pendingMatches = ExecuteQuery(new GetPendingMatchesQuery(websiteConfig.SeasonId));
        foreach (Roster pendingMatch in pendingMatches.Where(x => x.SkipRegistration == false))
        {
            context.PublishMessage(new RegisterPendingMatchTask(pendingMatch.Id !, pendingMatch.BitsMatchId));
        }

        return(Task.CompletedTask);
    }
Ejemplo n.º 7
0
        private IHttpActionResult Handle(RegisterMatchesMessage message)
        {
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

            Roster[] pendingMatches = ExecuteQuery(new GetPendingMatchesQuery(websiteConfig.SeasonId));
            foreach (Roster pendingMatch in pendingMatches.Where(x => x.SkipRegistration == false))
            {
                PublishMessage(new RegisterMatchMessage(pendingMatch.Id));
            }

            return(Ok());
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Override plugin directories for testing
        /// It will remove all test files when disposed
        /// </summary>
        /// <param name="pluginDirectories">Plugin directories, default is [ "App_Data/__TestPlugins" ]</param>
        /// <param name="plugins">Plugins, default is [ "PluginA", "PluginB" ]</param>
        /// <param name="extra">Extra data, default is empty</param>
        /// <param name="pluginDirectoryIndex">Which plugin directory will use to create plugins</param>
        public TestDirectoryLayout(
            IList <string> pluginDirectories   = null,
            IList <string> plugins             = null,
            IDictionary <string, object> extra = null,
            int pluginDirectoryIndex           = 0)
        {
            OverrideIoc   = Application.OverrideIoc();
            WebsiteConfig = new WebsiteConfig()
            {
                PluginDirectories = pluginDirectories ?? new List <string>()
                {
                    "App_Data/__TestPlugins"
                },
                Plugins = plugins ?? new List <string>()
                {
                    "PluginA", "PluginB"
                },
                Extra = extra ?? new Dictionary <string, object>()
            };
            CleanupPaths = new List <string>();
            // Mock WebsiteConfigManager, LocalPathManager, PluginManager, IFileStorage
            var configManagerMock = new WebsiteConfigManager();

            configManagerMock.WebsiteConfig = WebsiteConfig;
            Application.Ioc.Unregister <WebsiteConfigManager>();
            Application.Ioc.Unregister <LocalPathManager>();
            Application.Ioc.Unregister <PluginManager>();
            Application.Ioc.Unregister <LocalFileStorage>();
            Application.Ioc.Unregister <IFileStorage>();
            Application.Ioc.RegisterInstance(configManagerMock);
            Application.Ioc.RegisterMany <LocalPathManager>(ReuseType.Singleton);
            Application.Ioc.RegisterMany <PluginManager>(ReuseType.Singleton);
            Application.Ioc.RegisterMany <LocalFileStorage>(ReuseType.Singleton);
            // Create plugin directories and plugins
            var pathManager     = Application.Ioc.Resolve <LocalPathManager>();
            var pluginManager   = Application.Ioc.Resolve <PluginManager>();
            var pluginDirectory = pathManager.GetPluginDirectories()[pluginDirectoryIndex];

            foreach (var plugin in WebsiteConfig.Plugins)
            {
                var directory = Path.Combine(pluginDirectory, plugin);
                Directory.CreateDirectory(directory);
                pluginManager.Plugins.Add(PluginInfo.FromDirectory(directory));
            }
            foreach (var directory in pathManager.GetPluginDirectories())
            {
                CleanupPaths.Add(directory);
            }
            // Clear cache to prevent file content cache
            // On linux execution speed is so fast that cause file modify time are same between tests
            Application.Ioc.ResolveMany <ICacheCleaner>().ForEach(c => c.ClearCache());
        }
Ejemplo n.º 9
0
 public ResourceLink(
     StringWithDependencies urlWithDependencies,
     string httpMethod,
     IDictionary <string, StringWithDependencies> parametersWithDependencies,
     IDictionary <string, StringWithDependencies> headersWithDependencies,
     WebsiteConfig config,
     WebsiteJob job,
     ResourceLink referrerResourceLink
     ) : this(null, httpMethod, null, null, config, job, referrerResourceLink)
 {
     UrlWithDependencies        = urlWithDependencies;
     ParametersWithDependencies = parametersWithDependencies;
     HeadersWithDependencies    = headersWithDependencies;
 }
Ejemplo n.º 10
0
 public InitializationLink(
     StringWithDependencies urlWithDependencies,
     string httpMethod,
     IDictionary <string, StringWithDependencies> parametersWithDependencies,
     IDictionary <string, StringWithDependencies> headersWithDependencies,
     bool extractLinks,
     bool extractData,
     WebsiteConfig config,
     WebsiteJob job,
     CollectionDictionary <string, StringWithDependencies> preExtractedItemsWithDependencies = null
     )
     : base(urlWithDependencies, httpMethod, parametersWithDependencies, headersWithDependencies, extractLinks, extractData, config, job, preExtractedItemsWithDependencies, null)
 {
 }
Ejemplo n.º 11
0
 public InitializationLink(
     string url,
     string httpMethod,
     IDictionary <string, string> parameters,
     IDictionary <string, string> headers,
     bool extractLinks,
     bool extractData,
     WebsiteConfig config,
     WebsiteJob job,
     CollectionDictionary <string, string> preExtractedItems = null
     )
     : base(url, httpMethod, parameters, headers, extractLinks, extractData, config, job, preExtractedItems, null)
 {
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Find plugin path
        /// </summary>
        /// <param name="config">Website configuration</param>
        /// <param name="pluginName">Plugin name</param>
        /// <returns></returns>
        protected virtual string FindPluginDirectory(WebsiteConfig config, string pluginName)
        {
            var pluginDirectories = config.PluginDirectories
                                    .Select(d => Path.GetFullPath(Path.Combine(GetWebRoot(), d))).ToList();

            foreach (var dir in pluginDirectories)
            {
                var pluginDir = Path.Combine(dir, pluginName);
                if (Directory.Exists(pluginDir))
                {
                    return(pluginDir);
                }
            }
            throw new DirectoryNotFoundException($"Plugin directory for {pluginName} not found");
        }
Ejemplo n.º 13
0
        public ActionResult Edit(string id)
        {
            Roster roster = DocumentSession.Load <Roster>(id);

            if (roster == null)
            {
                throw new HttpException(404, "Roster not found");
            }
            if (roster.MatchResultId != null)
            {
                throw new HttpException(400, "Can not modify registered rosters");
            }
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

            ViewBag.TeamNamesAndLevels = websiteConfig.TeamNamesAndLevels;
            return(View(new CreateRosterViewModel(roster)));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Override plugin directories for testing
        /// It will remove all test files when disposed
        /// </summary>
        /// <param name="pluginDirectories">Plugin directories, default is [ "App_Data/__TestPlugins" ]</param>
        /// <param name="plugins">Plugins, default is [ "PluginA", "PluginB" ]</param>
        /// <param name="extra">Extra data, default is empty</param>
        /// <param name="pluginDirectoryIndex">Which plugin directory will use to create plugins</param>
        public TestDirectoryLayout(
            IList <string> pluginDirectories   = null,
            IList <string> plugins             = null,
            IDictionary <string, object> extra = null,
            int pluginDirectoryIndex           = 0)
        {
            OverrideIoc   = Application.OverrideIoc();
            WebsiteConfig = new WebsiteConfig()
            {
                PluginDirectories = pluginDirectories ?? new List <string>()
                {
                    "App_Data/__TestPlugins"
                },
                Plugins = plugins ?? new List <string>()
                {
                    "PluginA", "PluginB"
                },
                Extra = extra ?? new Dictionary <string, object>()
            };
            CleanupPaths = new List <string>();
            // Mock ConfigManager, PathConfig, PathManager, PluginManager
            var configManagerMock = Substitute.ForPartsOf <ConfigManager>();

            configManagerMock.WebsiteConfig.Returns(WebsiteConfig);
            Application.Ioc.Unregister <ConfigManager>();
            Application.Ioc.Unregister <PathManager>();
            Application.Ioc.Unregister <PluginManager>();
            Application.Ioc.RegisterInstance(configManagerMock);
            Application.Ioc.RegisterMany <PathManager>(ReuseType.Singleton);
            Application.Ioc.RegisterMany <PluginManager>(ReuseType.Singleton);
            // Create plugin directories and plugins
            var pathManager     = Application.Ioc.Resolve <PathManager>();
            var pluginManager   = Application.Ioc.Resolve <PluginManager>();
            var pluginDirectory = pathManager.GetPluginDirectories()[pluginDirectoryIndex];

            foreach (var plugin in WebsiteConfig.Plugins)
            {
                var directory = Path.Combine(pluginDirectory, plugin);
                Directory.CreateDirectory(directory);
                pluginManager.Plugins.Add(PluginInfo.FromDirectory(directory));
            }
            foreach (var directory in pathManager.GetPluginDirectories())
            {
                CleanupPaths.Add(directory);
            }
        }
Ejemplo n.º 15
0
 public DocumentLink(
     StringWithDependencies urlWithDependencies,
     string httpMethod,
     IDictionary <string, StringWithDependencies> parametersWithDependencies,
     IDictionary <string, StringWithDependencies> headersWithDependencies,
     bool extractLinks,
     bool extractData,
     WebsiteConfig config,
     WebsiteJob job,
     CollectionDictionary <string, StringWithDependencies> preExtractedItemsWithDependencies,
     DocumentLink referrerDocumentLink = null
     )
     : base(urlWithDependencies, httpMethod, parametersWithDependencies, headersWithDependencies, config, job, referrerDocumentLink)
 {
     ExtractLinks = extractLinks;
     ExtractData  = extractData;
     PreExtractedItemsWithDependencies = preExtractedItemsWithDependencies;
 }
Ejemplo n.º 16
0
 public DocumentLink
 (
     string url,
     string httpMethod,
     IDictionary <string, string> parameters,
     IDictionary <string, string> headers,
     bool extractLinks,
     bool extractData,
     WebsiteConfig config,
     WebsiteJob job,
     CollectionDictionary <string, string> preExtractedItems,
     DocumentLink referrerDocumentLink = null
 )
     : base(url, httpMethod, parameters, headers, config, job, referrerDocumentLink)
 {
     ExtractLinks      = extractLinks;
     ExtractData       = extractData;
     PreExtractedItems = preExtractedItems;
 }
Ejemplo n.º 17
0
 public ResourceLink(
     string url,
     string httpMethod,
     IDictionary <string, string> parameters,
     IDictionary <string, string> headers,
     WebsiteConfig config,
     WebsiteJob job,
     ResourceLink referrerResourceLink
     )
 {
     Url                  = url;
     HttpMethod           = httpMethod;
     Config               = config;
     Job                  = job;
     Parameters           = parameters;
     Headers              = headers;
     ReferrerResourceLink = referrerResourceLink;
     UserAgent            = referrerResourceLink?.UserAgent ?? config.CrawlingSettings.UserAgents.GetRandomElement();
 }
Ejemplo n.º 18
0
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // load website config to make sure it always migrates
        WebsiteConfig websiteContent = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

        if (websiteContent == null)
        {
            CompositionRoot.DocumentSession.Store(new WebsiteConfig(new WebsiteConfig.TeamNameAndLevel[0], false, -1, 2019));
        }

        // make sure there's an admin user
        if (CompositionRoot.DocumentSession.Load <User>(Models.User.AdminId) != null)
        {
            return;
        }

        // first launch
        Response.Redirect("/v1/welcome");
        Response.End();
    }
Ejemplo n.º 19
0
        public static DocumentProcessor CreateWebResponseParser(this WebsiteConfig websiteConfig, WebResponse webResponse, DocumentLink documentLink)
        {
            switch (websiteConfig.CrawlingSettings.DocumentType)
            {
            case Configuration.WebsiteConfigSections.WebsiteCrawlingSettings.DocumentTypes.HtmlCSS:
                return(new HtmlLocationCssDocumentProcessor(webResponse, documentLink));

            case Configuration.WebsiteConfigSections.WebsiteCrawlingSettings.DocumentTypes.HtmlXPath:
                return(new HtmlLocationXPathDocumentProcessor(webResponse, documentLink));

            case Configuration.WebsiteConfigSections.WebsiteCrawlingSettings.DocumentTypes.Xml:
                throw new NotImplementedException();

            case Configuration.WebsiteConfigSections.WebsiteCrawlingSettings.DocumentTypes.Json:
                throw new NotImplementedException();

            default:
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 20
0
    public override async Task Handle(HandlerContext <Command> context)
    {
        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);
        PlayerResult  playersResult = await CompositionRoot.BitsClient.GetPlayers(websiteConfig.ClubId);

        Player[] players = CompositionRoot.DocumentSession.Query <Player, PlayerSearch>()
                           .ToArray();

        // update existing players by matching on license number
        Dictionary <string, PlayerItem> playersByLicense = playersResult.Data.ToDictionary(x => x.LicNbr !);

        foreach (Player player in players.Where(x => x.PlayerItem != null))
        {
            if (playersByLicense.TryGetValue(player.PlayerItem !.LicNbr !, out PlayerItem playerItem))
            {
                player.PlayerItem = playerItem;
                _ = playersByLicense.Remove(player.PlayerItem.LicNbr !);
                Logger.InfoFormat(
                    "Updating player with existing PlayerItem {licNbr}",
                    player.PlayerItem.LicNbr);
            }
Ejemplo n.º 21
0
    public ActionResult Edit(string id, CreateRosterViewModel vm)
    {
        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

        if (!ModelState.IsValid)
        {
            ViewBag.TeamNamesAndLevels = websiteConfig.TeamNamesAndLevels;
            return(View(vm));
        }

        Roster roster = CompositionRoot.DocumentSession.Load <Roster>(id);

        if (roster == null)
        {
            throw new HttpException(404, "Roster not found");
        }

        if (roster.MatchResultId != null)
        {
            throw new HttpException(400, "Can not modify registered rosters");
        }

        roster.Location     = vm.Location;
        roster.Opponent     = vm.Opponent;
        roster.Season       = vm.Season;
        roster.Team         = vm.Team.Split(';')[0];
        roster.TeamLevel    = vm.Team.Split(';')[1];
        roster.Turn         = vm.Turn;
        roster.BitsMatchId  = vm.BitsMatchId;
        roster.IsFourPlayer = vm.IsFourPlayer;
        roster.Date         = ParseDate(vm.Date);
        if (vm.BitsMatchId == 0)
        {
            roster.OilPattern = new OilPatternInformation(vm.OilPatternName !, string.Empty);
        }

        return(RedirectToAction("Index"));
    }
Ejemplo n.º 22
0
        public async Task <ActionResult> CreateBitsVerify(VerifyBitsViewModel vm)
        {
            if (DocumentSession.Query <Roster, RosterSearchTerms>()
                .SingleOrDefault(x => x.BitsMatchId == vm.BitsMatchId) != null)
            {
                ModelState.AddModelError("BitsMatchId", "Matchen redan upplagd");
            }

            if (ModelState.IsValid == false)
            {
                return(View("CreateBits"));
            }

            int           season        = DocumentSession.LatestSeasonOrDefault(DateTime.Now.Year);
            WebsiteConfig websiteConfig = DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

            Infrastructure.Bits.Contracts.HeadInfo content = await bitsClient.GetHeadInfo(vm.BitsMatchId);

            ParseHeaderResult header = BitsParser.ParseHeader(content, websiteConfig.ClubId);

            ViewBag.TeamNamesAndLevels = websiteConfig.TeamNamesAndLevels;
            return(View(
                       "Create", new CreateRosterViewModel
            {
                Season = season,
                Turn = header.Turn,
                BitsMatchId = vm.BitsMatchId,
                Team = header.Team,
                IsFourPlayer = false,
                Opponent = header.Opponent,
                Date = header.Date.ToString(DateTimeFormat),
                Location = header.Location,
                OilPatternName = header.OilPattern.Name,
                OilPatternUrl = header.OilPattern.Url
            }));
        }
Ejemplo n.º 23
0
        public void Initialize(IRequestCultureFeature culture, string username, string password, bool ensureDbIsDeleted = false)
        {
            // Resets the configuration file in case it was modified
            Configuration.GlobalWebsiteConfig.ThemeName = "Default";



            /*---START Does not work on certain webhostings--- */

            //if (ensureDbIsDeleted) DatabaseContext.Database.EnsureDeleted();
            //DatabaseContext.Database.EnsureCreated();

            /*---END Does not work on certain webhostings--- */

            if (ensureDbIsDeleted)
            {
                DatabaseContext.Database.EnsureDeleted();
                DatabaseContext.Database.EnsureCreated();
            }
            else
            {
                DatabaseContext.Database.Migrate(); // creates the database - working solution for every webhosting
            }



            //Configuration.DbHelper = new DbHelper(DatabaseContext); // Old implementation without dependency injection



            // If there is at least one user, the DB was already seeded
            //if (DatabaseContext.Users.Any())
            //{
            //    return;   // DB has been seeded
            //}


            Category[] categories = new Category[]
            {
                new Category()
                {
                    Name = "Uncategorized"
                },
            };

            foreach (Category c in categories)
            {
                DatabaseContext.Categories.Add(c);
            }
//DatabaseContext.SaveChanges();



            // Demo article
            StreamReader sr             = new StreamReader(Env.Hosting.ContentRootPath + "/Areas/Admin/DemoDataResources/DemoArticle.txt");
            string       articleContent = sr.ReadToEnd();

            Article[] articles = new Article[]
            {
                new Article {
                    Name = "Lorem Ipsum", Publish = true, HtmlContent = articleContent, PublishDate = DateTime.Now, Category = categories[0], Keywords = "lorem, ipsum, dolor, sit, amet"
                },
            };

            //for (int i = 1; i <= 10000; i++)
            //{
            //    Article a = new Article { Name = "Ukázkový článek", Publish = true, HtmlContent = articleContent, PublishDate = DateTime.Now, Category = categories[0], Keywords = "článek, ukázka, demo" };
            //    DatabaseContext.Articles.Add(a);
            //}

            foreach (Article a in articles)
            {
                DatabaseContext.Articles.Add(a);
            }
            //DatabaseContext.SaveChanges();

            Role adminRole = new Role()
            {
                Name = "admin"
            };
            Role redactorRole = new Role()
            {
                Name = "redactor"
            };

            DatabaseContext.Roles.Add(adminRole);
            DatabaseContext.Roles.Add(redactorRole);

            //DatabaseContext.SaveChanges();

            User admin = new User()
            {
                Nickname = username, Username = username, Role = adminRole
            };
            string salt, hashedPassword;

            JasperSite.Models.Security.Authentication.HashPassword(password, out salt, out hashedPassword);
            admin.Password = hashedPassword;
            admin.Salt     = salt;
            DatabaseContext.Users.Add(admin);



//DatabaseContext.SaveChanges();

            // Settings
            Setting websiteNameSetting = new Setting()
            {
                Key = "WebsiteName", Value = "Lorem Ipsum"
            };

            _databaseContext.Settings.Add(websiteNameSetting);
            //DatabaseContext.SaveChanges();

            // Text blocks

            List <ThemeInfo> themesInfo = Configuration.ThemeHelper.GetInstalledThemesInfoByNameAndActive(culture);

            foreach (ThemeInfo ti in themesInfo)
            {
                Theme theme = new Theme()
                {
                    Name = ti.ThemeName
                };
                _databaseContext.Themes.Add(theme);
                //_databaseContext.SaveChanges();

                // Emulation of website configuration for every theme
                GlobalConfigDataProviderJson globalJsonProvider = new GlobalConfigDataProviderJson("jasper.json");
                GlobalWebsiteConfig          globalConfig       = new GlobalWebsiteConfig(globalJsonProvider);
                globalConfig.SetTemporaryThemeName(ti.ThemeName); // This will not write enytihing to the underlying .json file
                ConfigurationObjectProviderJson configurationObjectJsonProvider = new ConfigurationObjectProviderJson(globalConfig, "jasper.json");
                WebsiteConfig websiteConfig = new WebsiteConfig(configurationObjectJsonProvider);


                TextBlock textBlock1 = new TextBlock()
                {
                    Name = "WelcomePageTextBlock", Content = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas ipsum velit, consectetuer eu lobortis ut, dictum at dui."
                };
                TextBlock textBlock2 = new TextBlock()
                {
                    Name = "AboutPageTextBlock", Content = "Mauris metus. Aliquam in lorem sit amet leo accumsan lacinia. Integer lacinia."
                };
                TextBlock textBlock3 = new TextBlock()
                {
                    Name = "FooterPageTextBlock", Content = "Aenean vel massa quis mauris vehicula lacinia. Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
                };
                if (ti.ThemeName == "Default")
                {
                    // Demo text blocks
                    _databaseContext.TextBlocks.Add(textBlock1);
                    _databaseContext.TextBlocks.Add(textBlock2);
                    _databaseContext.TextBlocks.Add(textBlock3);
                    //_databaseContext.SaveChanges();

                    // DemoImages
                    string imgPath = Env.Hosting.ContentRootPath + "/Areas/Admin/DemoDataResources/demo_background.jpg";
                    byte[] bytes   = System.IO.File.ReadAllBytes(imgPath);
                    Image  img     = new Image();
                    img.Name = "Lorem ipsum";
                    img.InDb = true;

                    ImageData imgData = new ImageData()
                    {
                        Data = bytes
                    };

                    img.ImageData = imgData;

                    _databaseContext.Images.Add(img);
                    _databaseContext.ImageData.Add(imgData);

                    //_databaseContext.SaveChanges();
                }

                List <string> holders = websiteConfig.BlockHolders;
                foreach (string holderName in holders)
                {
                    BlockHolder blockHolder = new BlockHolder()
                    {
                        Name = holderName, ThemeId = theme.Id
                    };
                    _databaseContext.BlockHolders.Add(blockHolder);

                    if (ti.ThemeName == "Default")
                    {
                        if (holderName.Contains("Main"))
                        {
                            Holder_Block hb1 = new Holder_Block()
                            {
                                BlockHolder = blockHolder, TextBlock = textBlock1, Order = 1
                            };
                            _databaseContext.Holder_Block.Add(hb1);
                        }
                        else if (holderName.Contains("About"))
                        {
                            Holder_Block hb2 = new Holder_Block()
                            {
                                BlockHolder = blockHolder, TextBlock = textBlock2, Order = 1
                            };
                            _databaseContext.Holder_Block.Add(hb2);
                        }
                        else
                        {
                            Holder_Block hb3 = new Holder_Block()
                            {
                                BlockHolder = blockHolder, TextBlock = textBlock3, Order = 1
                            };
                            _databaseContext.Holder_Block.Add(hb3);
                        }
//_databaseContext.SaveChanges();
                    }
                }
            }


            // Add URL rewriting for articles

            UrlRewrite rule1 = new UrlRewrite()
            {
                ArticleId = articles[0].Id, Url = "first_article"
            };

            _databaseContext.UrlRewrite.Add(rule1);

            _databaseContext.SaveChanges();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// All manually deleted themes will be removed from the database,
        /// all unregistered themes will be added to the database,
        /// blockHolders in database will be synchronized with jasper.json
        /// </summary>
        /// <param name="Database"></param>
        /// <exception cref="ThemeHelperException"></exception>
        public void UpdateAllThemeRelatedData(DatabaseContext Database, IRequestCultureFeature culture)
        {
            try
            {
                DbHelper dbHelper = new DbHelper(Database);

                // Firstly, this will add all unregistered themes to the database
                dbHelper.AddThemesFromFolderToDatabase(dbHelper.CheckThemeFolderAndDatabaseIntegrity(culture), culture);

                //Secondly, all manually deleted themes will be removed from the DB
                List <string> themesToDelete = dbHelper.FindManuallyDeletedThemes(culture);
                foreach (string name in themesToDelete)
                {
                    dbHelper.DeleteThemeByName(name);
                }

                // All cached data will be updated
                Configuration.WebsiteConfig.RefreshData();

                // All blockHolders will be checked:
                // if they don't exist in jasper.json, all related data will be deleted from the DB
                // if they exist in jasper.json, everything in the DB will remain as is
                // if there are new blockHolders in jasper.json, they will be added to the DB


                // All themes info, even those that were already registered
                List <ThemeInfo> themesInfo = Configuration.ThemeHelper.GetInstalledThemesInfo(culture);


                foreach (ThemeInfo ti in themesInfo)
                {
                    // Find this theme in DB
                    Theme themeInDB                = dbHelper.GetAllThemes().Where(t => t.Name == ti.ThemeName).Single();
                    var   allBlockHolders          = dbHelper.GetAllBlockHolders();
                    var   blockHoldersForThisTheme = allBlockHolders.Where(bh => bh.ThemeId == themeInDB.Id);

                    // Emulation of website configuration for every theme
                    GlobalConfigDataProviderJson globalJsonProvider = new GlobalConfigDataProviderJson("jasper.json");
                    GlobalWebsiteConfig          globalConfig       = new GlobalWebsiteConfig(globalJsonProvider);
                    globalConfig.SetTemporaryThemeName(ti.ThemeName); // This will not write enytihing to the underlying .json file
                    ConfigurationObjectProviderJson configurationObjectJsonProvider = new ConfigurationObjectProviderJson(globalConfig, "jasper.json");
                    WebsiteConfig websiteConfig = new WebsiteConfig(configurationObjectJsonProvider);

                    List <string> holders = websiteConfig.BlockHolders;

                    // excess holders will be removed from DB
                    foreach (BlockHolder holderFromDb in blockHoldersForThisTheme)
                    {
                        if (!holders.Contains(holderFromDb.Name))
                        {
                            Database.BlockHolders.Remove(holderFromDb);
                            Database.SaveChanges();
                        }
                    }

                    // Newly added holders will be saved into the database
                    foreach (string holderName in holders)
                    {
                        bool isHolderInDB = false;

                        foreach (BlockHolder singleBlockHolderInDb in blockHoldersForThisTheme)
                        {
                            if (singleBlockHolderInDb.Name == holderName)
                            {
                                isHolderInDB = true;
                            }
                        }

                        if (!isHolderInDB)
                        {
                            // New blockHolder will be registered into the DB
                            Database.BlockHolders.Add(new BlockHolder()
                            {
                                Name = holderName, ThemeId = themeInDB.Id
                            });
                        }
                    }
                    Database.SaveChanges();
                }
            }
            catch {
                throw new ThemeHelperException();
            }
        }
Ejemplo n.º 25
0
    public override async Task Handle(HandlerContext <Command> context)
    {
        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

        Logger.InfoFormat(
            "Importing BITS season {seasonId} for {teamFullName} (ClubId={clubId})",
            websiteConfig.SeasonId,
            CompositionRoot.CurrentTenant.TeamFullName,
            websiteConfig.ClubId);
        RosterSearchTerms.Result[] rosterSearchTerms =
            CompositionRoot.DocumentSession.Query <RosterSearchTerms.Result, RosterSearchTerms>()
            .Where(x => x.Season == websiteConfig.SeasonId)
            .Where(x => x.BitsMatchId != 0)
            .ProjectFromIndexFieldsInto <RosterSearchTerms.Result>()
            .ToArray();
        Roster[] rosters = CompositionRoot.DocumentSession.Load <Roster>(
            rosterSearchTerms.Select(x => x.Id));
        HashSet <int> foundMatchIds = new();

        // Team
        Logger.Info("Fetching teams");
        TeamResult[] teams = await CompositionRoot.BitsClient.GetTeam(
            websiteConfig.ClubId,
            websiteConfig.SeasonId);

        foreach (TeamResult teamResult in teams)
        {
            // Division
            Logger.Info("Fetching divisions");
            DivisionResult[] divisionResults = await CompositionRoot.BitsClient.GetDivisions(
                teamResult.TeamId,
                websiteConfig.SeasonId);

            // Match
            if (divisionResults.Length != 1)
            {
                throw new Exception($"Unexpected number of divisions: {divisionResults.Length}");
            }

            DivisionResult divisionResult = divisionResults[0];
            Logger.Info("Fetching match rounds");
            MatchRound[] matchRounds = await CompositionRoot.BitsClient.GetMatchRounds(
                teamResult.TeamId,
                divisionResult.DivisionId,
                websiteConfig.SeasonId);

            Dictionary <int, MatchRound> dict = matchRounds.ToDictionary(x => x.MatchId);
            foreach (int key in dict.Keys)
            {
                _ = foundMatchIds.Add(key);
            }

            // update existing rosters
            foreach (Roster roster in rosters.Where(x => dict.ContainsKey(x.BitsMatchId)))
            {
                Logger.Info($"Updating roster {roster.Id}");
                MatchRound matchRound = dict[roster.BitsMatchId];
                roster.OilPattern = OilPatternInformation.Create(
                    matchRound.MatchOilPatternName !,
                    matchRound.MatchOilPatternId);
                roster.Date             = matchRound.MatchDate !.ToDateTime(matchRound.MatchTime);
                roster.Turn             = matchRound.MatchRoundId;
                roster.MatchTimeChanged = matchRound.MatchStatus == 2;
                if (matchRound.HomeTeamClubId == websiteConfig.ClubId)
                {
                    roster.Team      = matchRound.MatchHomeTeamAlias !;
                    roster.TeamLevel = roster.Team.Substring(roster.Team.LastIndexOf(' ') + 1);
                    roster.Opponent  = matchRound.MatchAwayTeamAlias !;
                }
                else if (matchRound.AwayTeamClubId == websiteConfig.ClubId)
                {
                    roster.Team      = matchRound.MatchAwayTeamAlias !;
                    roster.TeamLevel = roster.Team.Substring(roster.Team.LastIndexOf(' ') + 1);
                    roster.Opponent  = matchRound.MatchHomeTeamAlias !;
                }
                else
                {
                    throw new Exception($"Unknown clubs: {matchRound.HomeTeamClubId} {matchRound.AwayTeamClubId}");
                }

                roster.Location = matchRound.MatchHallName !;
            }

            // add missing rosters
            HashSet <int> existingMatchIds = new(rosters.Select(x => x.BitsMatchId));
            foreach (int matchId in dict.Keys.Where(x => existingMatchIds.Contains(x) == false))
            {
                Logger.InfoFormat("Adding match {matchId}", matchId);
                MatchRound matchRound = dict[matchId];
                string     team;
                string     opponent;
                if (matchRound.HomeTeamClubId == websiteConfig.ClubId)
                {
                    team     = matchRound.MatchHomeTeamAlias !;
                    opponent = matchRound.MatchAwayTeamAlias !;
                }
                else if (matchRound.AwayTeamClubId == websiteConfig.ClubId)
                {
                    team     = matchRound.MatchAwayTeamAlias !;
                    opponent = matchRound.MatchHomeTeamAlias !;
                }
                else
                {
                    throw new Exception($"Unknown clubs: {matchRound.HomeTeamClubId} {matchRound.AwayTeamClubId}");
                }

                Roster roster = new(
                    matchRound.MatchSeason,
                    matchRound.MatchRoundId,
                    matchRound.MatchId,
                    team !,
                    team.Substring(team.LastIndexOf(' ') + 1),
                    matchRound.MatchHallName !,
                    opponent,
                    matchRound.MatchDate !.ToDateTime(matchRound.MatchTime),
                    matchRound.MatchNbrOfPlayers == 4,
                    OilPatternInformation.Create(matchRound.MatchOilPatternName !, matchRound.MatchOilPatternId))
                {
                    MatchTimeChanged = matchRound.MatchStatus == 2
                };
                CompositionRoot.DocumentSession.Store(roster);
            }
        }

        // remove extraneous rosters
        Roster[] toRemove = rosters
                            .Where(x => foundMatchIds.Contains(x.BitsMatchId) == false &&
                                   x.MatchResultId is null &&
                                   x.Turn <= 20)
                            .ToArray();
        if (toRemove.Any())
        {
            foreach (Roster roster in toRemove)
            {
                CompositionRoot.DocumentSession.Delete(roster);
            }

            string joined = string.Join(
                ",",
                toRemove.Select(x => $"Id={x.Id} BitsMatchId={x.BitsMatchId}"));
            Logger.InfoFormat("Rosters to remove: {joined}", joined);
            string    body  = $"Rosters to remove: {joined}";
            SendEmail email = SendEmail.ToAdmin(
                $"Removed rosters for {CompositionRoot.CurrentTenant.TeamFullName}",
                body);
            await CompositionRoot.EmailService.SendAsync(email);
        }
    }
 protected override void ResponseCallback(HttpWebResponse webResponse)
 {
     Config = Parse(webResponse, BaseParser.WebsiteConfigParser, new WebsiteConfigParser(null));
     SitAndWait.Set();
 }
Ejemplo n.º 27
0
        public void OnRequest()
        {
            var handler = new DefaultErrorHandler();

            using (Application.OverrideIoc()) {
                var logManagerMock = Substitute.For <LogManager>();
                var config         = new WebsiteConfig()
                {
                    Extra = new Dictionary <string, object>()
                };
                var configManagerMock = Substitute.For <WebsiteConfigManager>();
                configManagerMock.WebsiteConfig.Returns(config);
                Application.Ioc.Unregister <LogManager>();
                Application.Ioc.RegisterInstance(logManagerMock);
                Application.Ioc.Unregister <WebsiteConfigManager>();
                Application.Ioc.RegisterInstance(configManagerMock);
                // Only return message if error occurs with ajax request
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    request.headers["X-Requested-With"] = "XMLHttpRequest";
                    handler.OnError(new ArgumentException("some message"));
                    Assert.Equals(response.GetContentsFromBody(), "some message");
                }
                // Display status and message if the error is HttpException
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new HttpException(404, "wrong address"));
                    var contents = response.GetContentsFromBody();
                    Assert.IsTrueWith(
                        contents.Contains("404 wrong address") && !contents.Contains("<pre>"), contents);
                }
                // Display full exception dependent on website configuration
                config.Extra[ExtraConfigKeys.DisplayFullExceptionForRequest] = true;
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new ArgumentException("500 some error"));
                    var contents = response.GetContentsFromBody();
                    Assert.IsTrueWith(
                        contents.Contains("500 some error") && contents.Contains("<pre>"), contents);
                }
                config.Extra[ExtraConfigKeys.DisplayFullExceptionForRequest] = false;
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new ArgumentException("500 some error"));
                    var contents = response.GetContentsFromBody();
                    Assert.IsTrueWith(
                        contents.Contains("500 some error") && !contents.Contains("<pre>"), contents);
                }
                // Test error logging
                logManagerMock.ClearReceivedCalls();
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new HttpException(401, "user error"));
                    logManagerMock.DidNotReceiveWithAnyArgs().LogError(null);
                }
                logManagerMock.ClearReceivedCalls();
                using (HttpManager.OverrideContext("", "GET")) {
                    var request  = (HttpRequestMock)HttpManager.CurrentContext.Request;
                    var response = (HttpResponseMock)HttpManager.CurrentContext.Response;
                    handler.OnError(new HttpException(500, "server error"));
                    logManagerMock.ReceivedWithAnyArgs().LogError(null);
                }
            }
        }
Ejemplo n.º 28
0
    public override async Task Handle(HandlerContext <Command> context)
    {
        Roster roster = CompositionRoot.DocumentSession.Load <Roster>(context.Payload.RosterId);

        if (roster.IsVerified && context.Payload.Force == false)
        {
            return;
        }

        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);
        HeadInfo      result        = await CompositionRoot.BitsClient.GetHeadInfo(roster.BitsMatchId);

        ParseHeaderResult header = BitsParser.ParseHeader(result, websiteConfig.ClubId);

        // chance to update roster values
        Roster.Update update = new(
            Roster.ChangeType.VerifyMatchMessage,
            "system")
        {
            OilPattern = header.OilPattern,
            Date       = header.Date,
            Opponent   = header.Opponent,
            Location   = header.Location
        };
        if (roster.MatchResultId != null)
        {
            // update match result values
            BitsMatchResult bitsMatchResult = await CompositionRoot.BitsClient.GetBitsMatchResult(roster.BitsMatchId);

            Player[] players = CompositionRoot.DocumentSession.Query <Player, PlayerSearch>()
                               .ToArray()
                               .Where(x => x.PlayerItem?.LicNbr != null)
                               .ToArray();
            BitsParser parser = new(players);
            if (roster.IsFourPlayer)
            {
                MatchResult4?matchResult = CompositionRoot.EventStoreSession.Load <MatchResult4>(roster.MatchResultId);
                Parse4Result?parseResult = parser.Parse4(bitsMatchResult, websiteConfig.ClubId);
                update.Players = parseResult !.GetPlayerIds();
                bool isVerified = matchResult !.Update(
                    t => context.PublishMessage(t),
                    roster,
                    parseResult.TeamScore,
                    parseResult.OpponentScore,
                    roster.BitsMatchId,
                    parseResult.CreateMatchSeries(),
                    players);
                update.IsVerified = isVerified;
            }
            else
            {
                MatchResult?matchResult =
                    CompositionRoot.EventStoreSession.Load <MatchResult>(roster.MatchResultId);
                ParseResult?parseResult = parser.Parse(bitsMatchResult, websiteConfig.ClubId);
                update.Players = parseResult !.GetPlayerIds();
                Dictionary <string, ResultForPlayerIndex.Result> resultsForPlayer =
                    CompositionRoot.DocumentSession.Query <ResultForPlayerIndex.Result, ResultForPlayerIndex>()
                    .Where(x => x.Season == roster.Season)
                    .ToArray()
                    .ToDictionary(x => x.PlayerId);
                MatchSerie[] matchSeries = parseResult.CreateMatchSeries();
                bool         isVerified  = matchResult !.Update(
                    t => context.PublishMessage(t),
                    roster,
                    parseResult.TeamScore,
                    parseResult.OpponentScore,
                    matchSeries,
                    parseResult.OpponentSeries,
                    players,
                    resultsForPlayer);
                update.IsVerified = isVerified;
            }
        }

        _ = roster.UpdateWith(context.CorrelationId, update);
    }
Ejemplo n.º 29
0
    public const double TotalMoneyInterval = 60 * 60 * 1000; //one hour

    public static async Task Main(string[] args)
    {
        WebsiteConfig config = await GetConfig <WebsiteConfig>();

        CocaBotContext ds = new();

        ds.Database.EnsureCreated();

        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddCors();
        builder.Services.AddDistributedMemoryCache();
        builder.Services.AddDbContextPool <CocaBotPoolContext>((serviceProvider, options) =>
        {
            options.UseNpgsql(CocaBotPoolContext.ConnectionString);
        });

        builder.Services.AddHttpClient();

        builder.Services.AddRazorPages();

        var app = builder.Build();

        if (app.Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // global cors policy
        app.UseCors(x => x
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .SetIsOriginAllowed(origin => true) // allow any origin
                    .AllowCredentials());               // allow credentials

        app.UseStaticFiles();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });

        app.MapGet("/discord/getsvid", async(CocaBotPoolContext db, ulong id) =>
        {
            string svid = await db.Users.Where(x => x.Discord == id).Select(x => x.SVID).SingleOrDefaultAsync();
            return(svid is not null ? svid : "");
        });

        app.MapGet("/valour/getsvid", async(CocaBotPoolContext db, ulong id) =>
        {
            string svid = await db.Users.Where(x => x.Valour == id).Select(x => x.SVID).SingleOrDefaultAsync();
            return(svid is not null ? svid : "");
        });

        app.MapGet("/Transactions/Get", (CocaBotPoolContext db, int amount) =>
                   db.Transactions.OrderByDescending(x => x.Count)
                   .Take(amount));

        app.MapGet("/Transactions/GetFrom", async(CocaBotPoolContext db, string svid, int amount) =>
                   await db.Transactions.Where(x => x.FromAccount == svid)
                   .OrderByDescending(x => x.Count)
                   .Take(amount)
                   .ToListAsync());

        app.MapGet("/Transactions/GetTo", async(CocaBotPoolContext db, string svid, int amount) =>
                   await db.Transactions.Where(x => x.ToAccount == svid)
                   .OrderByDescending(x => x.Count)
                   .Take(amount)
                   .ToListAsync());

        app.MapGet("/Transactions/Filter", Filter);

        app.MapGet("/Transactions/SumFilter", SumFilter);

        app.Run();
    }
Ejemplo n.º 30
0
    public override async Task Handle(HandlerContext <Command> context)
    {
        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load <WebsiteConfig>(WebsiteConfig.GlobalId);

        Player[] players =
            CompositionRoot.DocumentSession.Query <Player, PlayerSearch>()
            .ToArray()
            .Where(x => x.PlayerItem?.LicNbr != null)
            .ToArray();
        Roster pendingMatch = CompositionRoot.DocumentSession.Load <Roster>(context.Payload.RosterId);

        try
        {
            BitsParser      parser          = new(players);
            BitsMatchResult bitsMatchResult = await CompositionRoot.BitsClient.GetBitsMatchResult(pendingMatch.BitsMatchId);

            if (bitsMatchResult.HeadInfo.MatchFinished == false)
            {
                Logger.InfoFormat(
                    "Match {bitsMatchId} not yet finished",
                    pendingMatch.BitsMatchId);
                return;
            }

            if (pendingMatch.IsFourPlayer)
            {
                Parse4Result?parse4Result = parser.Parse4(bitsMatchResult, websiteConfig.ClubId);
                if (parse4Result != null)
                {
                    if (parse4Result.Series.Length != 4 && parse4Result.Turn <= 20)
                    {
                        Logger.InfoFormat(
                            "detected unfinished match: {length} series have been registered",
                            parse4Result.Series.Length);
                        return;
                    }

                    List <string> allPlayerIds = parse4Result.GetPlayerIds();
                    pendingMatch.SetPlayers(allPlayerIds);
                    await context.ExecuteCommand(
                        new RegisterMatch4CommandHandler.Command(pendingMatch.Id !, parse4Result, null, null));
                }
            }
            else
            {
                ParseResult?parseResult = parser.Parse(bitsMatchResult, websiteConfig.ClubId);
                if (parseResult != null)
                {
                    if (parseResult.Series.Length != 4 && parseResult.Turn <= 20)
                    {
                        Logger.InfoFormat(
                            "detected unfinished match: {length} series have been registered",
                            parseResult.Series.Length);
                        return;
                    }

                    List <string> allPlayerIds = parseResult.GetPlayerIds();
                    pendingMatch.SetPlayers(allPlayerIds);
                    await context.ExecuteCommand(
                        new RegisterMatchCommandHandler.Command(pendingMatch.Id !, parseResult));
                }
            }
        }
        catch (Exception e)
        {
            Logger.Warn("Unable to auto-register match", e);
            ErrorSignal
            .FromCurrentContext()
            ?.Raise(new Exception($"Unable to auto register match {pendingMatch.Id} ({pendingMatch.BitsMatchId})", e));
        }
    }