Esempio n. 1
0
 public InitViewModel(Window view, DataManager dataManager, CreateFactory createFactory) : base(dataManager)
 {
     NewCommand            = new RelayCommand((o) => New(false), (o) => true);
     NewOnlineCommand      = new RelayCommand((o) => New(true), (o) => IsOnline);
     PlayCommand           = new RelayCommand((o) => Play(false), (o) => true);
     PlayOnlineCommand     = new RelayCommand((o) => Play(true), (o) => IsOnline);
     ExitCommand           = new RelayCommand((o) => Exit(), (o) => true);
     _view                 = view;
     _creteFactory         = createFactory;
     ServerStatusViewModel = new ServerStatusViewModel();
 }
        public ServerStatusViewModel GetServerStatus()
        {
            _logger.LogInformation("(Web)刷新服务器当前状态");
            var model = new ServerStatusViewModel
            {
                version    = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                downloader = _configuration["Downloader"],
                rules      = _rulesContainer.LocalRules.ToArray()
            };

            return(model);
        }
Esempio n. 3
0
        public ActionResult ServerStatus()
        {
            // hack fix me
            var api = new PeerDiscoveryController(new TerrariumDbContext());

            var vm = new ServerStatusViewModel
            {
                IsDatabaseUp = Database.Exists("TerrariumDbContext"),
                PeerCount    = api.GetNumPeers("", "")
            };

            return(PartialView("_ServerStatus", vm));
        }
Esempio n. 4
0
        public async Task <ServerStatusAllViewModel> Get()
        {
            var result = new ServerStatusAllViewModel();

            foreach (var context in _contextManager.Servers)
            {
                var serverContext = _contextManager.GetServer(context.Config.Key);
                var status        = serverContext.Steam.GetServerStatusCached();
                if (status == null || status.Item1 == null || status.Item2 == null)
                {
                    //Server status is currently unavailable
                }
                else
                {
                    var info        = status.Item1;
                    var rules       = status.Item2;
                    var playerinfos = status.Item3;

                    var m               = new Regex(@"^(?<name>.+?)\s+-\s+\(v(?<version>\d+\.\d+)\)$", RegexOptions.IgnoreCase | RegexOptions.Singleline).Match(info.Name);
                    var name            = m.Success ? m.Groups["name"].Value : info.Name;
                    var version         = m.Success ? m.Groups["version"] : null;
                    var currentTime     = rules.FirstOrDefault(x => x.Name == "DayTime_s")?.Value;
                    var tamedDinosCount = context.TamedCreatures?.Count();
                    //var uploadedDinosCount = _context.Cluster?.Creatures?.Count();
                    var wildDinosCount = context.WildCreatures?.Count();
                    //var tamedDinosMax = 6000; //todo: remove hardcoded value
                    var structuresCount = context.Structures?.Count();
                    var totalPlayers    = context.Players?.Count();
                    var totalTribes     = context.Tribes?.Count();

                    //server uptime
                    //DateTime? serverStarted = null;
                    //try
                    //{
                    //    serverStarted = Process.GetProcessesByName(_constants.ArkServerProcessName)?.FirstOrDefault()?.StartTime;

                    //}
                    //catch { /* ignore exceptions */ }

                    var nextUpdate       = context.ApproxTimeUntilNextUpdate;
                    var nextUpdateTmp    = nextUpdate?.ToStringCustom();
                    var nextUpdateString = (nextUpdate.HasValue ? (!string.IsNullOrWhiteSpace(nextUpdateTmp) ? $"~{nextUpdateTmp}" : "waiting for new update ...") : null);
                    var lastUpdate       = context.LastUpdate;
                    var lastUpdateString = lastUpdate.ToStringWithRelativeDay();

                    var sr = new ServerStatusViewModel
                    {
                        Key                = context.Config.Key,
                        Name               = name,
                        Address            = info.Address,
                        Version            = version.ToString(),
                        OnlinePlayerCount  = info.Players,
                        OnlinePlayerMax    = info.MaxPlayers,
                        MapName            = info.Map,
                        InGameTime         = currentTime,
                        TamedCreatureCount = tamedDinosCount ?? 0,
                        WildCreatureCount  = wildDinosCount ?? 0,
                        StructureCount     = structuresCount ?? 0,
                        PlayerCount        = totalPlayers ?? 0,
                        TribeCount         = totalTribes ?? 0,
                        LastUpdate         = lastUpdateString,
                        NextUpdate         = nextUpdateString
                    };

                    var players = playerinfos?.Where(x => !string.IsNullOrEmpty(x.Name)).ToArray() ?? new PlayerInfo[] { };
                    using (var db = _databaseContextFactory.Create())
                    {
                        Dictionary <string, Tuple <ArkPlayer, Database.Model.User, User, long?, TimeSpan, ArkTribe> > d = null;
                        if (context.Players != null)
                        {
                            var playerNames = players.Select(x => x.Name).ToArray();
                            d = context.Players.Where(x => playerNames.Contains(x.Name, StringComparer.Ordinal)).Select(x =>
                            {
                                long steamId;
                                return(new Tuple <ArkPlayer, Database.Model.User, User, long?, TimeSpan, ArkTribe>(
                                           x,
                                           null,
                                           null,
                                           long.TryParse(x.SteamId, out steamId) ? steamId : (long?)null,
                                           TimeSpan.Zero, null));
                            }).ToDictionary(x => x.Item1.Name, StringComparer.OrdinalIgnoreCase);

                            var ids      = new List <ulong>();
                            var steamIds = d.Values.Select(x => x.Item4).Where(x => x != null).ToArray();
                            foreach (var user in db.Users.Where(y => steamIds.Contains(y.SteamId)))
                            {
                                var item = d.Values.FirstOrDefault(x => x.Item4 == user.SteamId);
                                if (item == null)
                                {
                                    continue;
                                }

                                ids.Add(item.Item1.Id);

                                var discordUser         = (User)null;        //e.User?.Client?.Servers?.Select(x => x.GetUser((ulong)user.DiscordId)).FirstOrDefault();
                                var playedLastSevenDays = TimeSpan.MinValue; //TimeSpan.FromSeconds(user?.Played?.OrderByDescending(x => x.Date).Take(7).Sum(x => x.TimeInSeconds) ?? 0);

                                d[item.Item1.Name] = Tuple.Create(item.Item1, user, discordUser, item.Item4, playedLastSevenDays, item.Item1.TribeId.HasValue ? context.Tribes?.FirstOrDefault(x => x.Id == item.Item1.TribeId.Value) : null);
                            }

                            var remaining = d.Values.Where(x => !ids.Contains(x.Item1.Id)).Where(x => x.Item4 != null).Select(x => x.Item4.Value).ToArray();
                            foreach (var user in db.Played.Where(x => x.SteamId.HasValue && remaining.Contains(x.SteamId.Value))
                                     .GroupBy(x => x.SteamId)
                                     .Select(x => new { key = x.Key, items = x.OrderByDescending(y => y.Date).Take(7).ToList() })
                                     .ToArray())
                            {
                                var item = d.Values.FirstOrDefault(x => x.Item4 == user.key);
                                if (item == null)
                                {
                                    continue;
                                }

                                var playedLastSevenDays = TimeSpan.FromSeconds(user?.items?.Sum(x => x.TimeInSeconds) ?? 0);
                                d[item.Item1.Name] = Tuple.Create(item.Item1, item.Item2, item.Item3, item.Item4, playedLastSevenDays, item.Item1.TribeId.HasValue ? context.Tribes?.FirstOrDefault(x => x.Id == item.Item1.TribeId.Value) : null);
                            }
                        }

                        //var playerslist = players.Select(x => {
                        //    var extra = d.ContainsKey(x.Name) ? d[x.Name] : null;
                        //    return new
                        //    {
                        //        Steam = x.Name,
                        //        Name = extra?.Item1?.Name,
                        //        Tribe = extra?.Item1?.TribeName,
                        //        Discord = extra != null && extra.Item3 != null ? $"{extra.Item3.Name}#{extra.Item3.Discriminator}" : null,
                        //        TimeOnline = x.Time.ToStringCustom(),
                        //        PlayedLastSevenDays = extra != null && extra.Item5.TotalMinutes > 1 ? extra?.Item5.ToStringCustom() : null
                        //    };
                        //}).ToArray();

                        foreach (var player in players)
                        {
                            var extra = d?.ContainsKey(player.Name) == true ? d[player.Name] : null;
                            sr.OnlinePlayers.Add(new OnlinePlayerViewModel
                            {
                                SteamName         = player.Name,
                                CharacterName     = extra?.Item1?.Name,
                                TribeName         = extra?.Item6?.Name,
                                DiscordName       = extra != null && extra.Item3 != null ? $"{extra.Item3.Name}#{extra.Item3.Discriminator}" : null,
                                TimeOnline        = player.Time.ToStringCustom(),
                                TimeOnlineSeconds = (int)Math.Round(player.Time.TotalSeconds)
                            });
                        }
                    }

                    result.Servers.Add(sr);
                }
            }

            foreach (var context in _contextManager.Clusters)
            {
                var cc = new ClusterStatusViewModel
                {
                    Key        = context.Config.Key,
                    ServerKeys = _contextManager.Servers
                                 .Where(x => x.Config.Cluster.Equals(context.Config.Key, StringComparison.OrdinalIgnoreCase))
                                 .Select(x => x.Config.Key).ToArray()
                };
                result.Clusters.Add(cc);
            }

            return(result);
        }
Esempio n. 5
0
        public async Task <ServerStatusAllViewModel> Get()
        {
            var demoMode = IsDemoMode() ? new DemoMode() : null;

            var anonymize = _config.AnonymizeWebApiData;
            var user      = WebApiHelper.GetUser(Request, _config);

            if (anonymize)
            {
                var serverContext = _contextManager.Servers.FirstOrDefault();
                var player        = serverContext?.Players.Where(x =>
                                                                 x.Tribe != null &&
                                                                 x.Tribe.Creatures.Any(y => y.IsBaby) &&
                                                                 x.Tribe.Structures.OfType <ArkStructureCropPlot>().Any() &&
                                                                 x.Tribe.Structures.OfType <ArkStructureElectricGenerator>().Any()
                                                                 ).OrderByDescending(x => x.Creatures.Length).FirstOrDefault();

                if (player == null)
                {
                    user = null;
                }
                else
                {
                    user.Name    = player.Name;
                    user.SteamId = player.SteamId;
                    user.Roles   = _config.AccessControl.SelectMany(x => x.Value.Values)
                                   .SelectMany(x => x)
                                   .Distinct(StringComparer.OrdinalIgnoreCase)
                                   .OrderBy(x => x)
                                   .ToArray();
                }
            }

            var result = new ServerStatusAllViewModel {
                User = user, AccessControl = BuildViewModelForAccessControl(_config)
            };

            foreach (var context in _contextManager.Servers)
            {
                var serverContext = _contextManager.GetServer(context.Config.Key);
                var status        = serverContext.Steam.GetServerStatusCached();
                //if (status == null || status.Item1 == null || status.Item2 == null)
                //{
                //    //Server status is currently unavailable
                //}
                //else
                //{
                var info        = status?.Item1;
                var rules       = status?.Item2;
                var playerinfos = status?.Item3;

                var m                  = info != null ? new Regex(@"^(?<name>.+?)\s+-\s+\(v(?<version>\d+\.\d+)\)?$", RegexOptions.IgnoreCase | RegexOptions.Singleline).Match(info.Name) : null;
                var name               = m?.Success == true ? m.Groups["name"].Value : (info?.Name ?? context.Config.Key);
                var version            = m?.Success == true ? m.Groups["version"] : null;
                var currentTime        = rules?.FirstOrDefault(x => x.Name == "DayTime_s")?.Value;
                var tamedDinosCount    = context.TamedCreatures?.Count();
                var uploadedDinosCount = context.CloudCreatures?.Count();
                var wildDinosCount     = context.WildCreatures?.Count();
                //var tamedDinosMax = 6000; //todo: remove hardcoded value
                var structuresCount = context.Structures?.Count();
                var totalPlayers    = context.Players?.Count();
                var totalTribes     = context.Tribes?.Count();
                var serverStarted   = _serverService.GetServerStartTime(context.Config.Key);

                var nextUpdate       = context.ApproxTimeUntilNextUpdate;
                var nextUpdateTmp    = nextUpdate?.ToStringCustom();
                var nextUpdateString = (nextUpdate.HasValue ? (!string.IsNullOrWhiteSpace(nextUpdateTmp) ? $"~{nextUpdateTmp}" : "waiting for new update ...") : null);
                var lastUpdate       = context.LastUpdate;
                var lastUpdateString = lastUpdate.ToStringWithRelativeDay();

                var anonymizedServer = anonymize ? _anonymizeData.GetServer(context.Config.Key) : null;
                var sr = new ServerStatusViewModel
                {
                    Key                = anonymizedServer?.Key ?? context.Config.Key,
                    Name               = anonymizedServer?.Name ?? name,
                    Address            = anonymizedServer?.Address ?? context.Config.DisplayAddress ?? info?.Address,
                    Version            = version?.ToString(),
                    OnlinePlayerCount  = info?.Players ?? 0,
                    OnlinePlayerMax    = info?.MaxPlayers ?? 0,
                    MapName            = info?.Map,
                    InGameTime         = currentTime,
                    TamedCreatureCount = tamedDinosCount ?? 0,
                    CloudCreatureCount = uploadedDinosCount ?? 0,
                    WildCreatureCount  = wildDinosCount ?? 0,
                    StructureCount     = structuresCount ?? 0,
                    PlayerCount        = totalPlayers ?? 0,
                    TribeCount         = totalTribes ?? 0,
                    LastUpdate         = lastUpdateString,
                    NextUpdate         = nextUpdateString,
                    ServerStarted      = serverStarted
                };

                if (HasFeatureAccess("home", "online"))
                {
                    var onlineplayers = playerinfos?.Where(x => !string.IsNullOrEmpty(x.Name)).ToArray() ?? new PlayerInfo[] { };
                    if (anonymize)
                    {
                        int n = 0;
                        foreach (var player in context.Players.OrderByDescending(x => x.LastActiveTime).Take(onlineplayers.Length))
                        {
                            sr.OnlinePlayers.Add(new OnlinePlayerViewModel
                            {
                                SteamName         = player.Name,
                                CharacterName     = player.CharacterName,
                                TribeName         = player.Tribe?.Name,
                                DiscordName       = null,
                                TimeOnline        = onlineplayers[n].Time.ToStringCustom(),
                                TimeOnlineSeconds = (int)Math.Round(onlineplayers[n].Time.TotalSeconds)
                            });

                            n++;
                        }
                    }
                    else
                    {
                        using (var db = _databaseContextFactory.Create())
                        {
                            // Names of online players (steam does not provide ids)
                            var onlineplayerNames = onlineplayers.Select(x => x.Name).ToArray();

                            // Get the player data for each name (null when no matching name or when multiple players share the same name)
                            var onlineplayerData = context.Players != null ? (from k in onlineplayerNames join p in context.Players on k equals p.Name into grp select grp.Count() == 1 ? grp.ElementAt(0) : null).ToArray() : new ArkPlayer[] { };

                            // Parse all steam ids
                            var parsedSteamIds = onlineplayerData.Select(x => { long steamId; return(x?.SteamId != null ? long.TryParse(x.SteamId, out steamId) ? steamId : (long?)null : null); }).ToArray();

                            // Get the player data for each name
                            var databaseUsers = (from k in parsedSteamIds join u in db.Users on k equals u?.SteamId into grp select grp.FirstOrDefault()).ToArray();

                            // Get the discord users
                            var discordUsers = databaseUsers.Select(x => x != null ? _discordManager.GetDiscordUserNameById((ulong)x.DiscordId) : null).ToArray();

                            int n = 0;
                            foreach (var player in onlineplayers)
                            {
                                var extra          = onlineplayerData.Length > n ? new { player = onlineplayerData[n], user = databaseUsers[n], discordName = discordUsers[n] } : null;
                                var demoPlayerName = demoMode?.GetPlayerName();

                                sr.OnlinePlayers.Add(new OnlinePlayerViewModel
                                {
                                    SteamName         = demoPlayerName ?? player.Name,
                                    CharacterName     = demoPlayerName ?? extra?.player?.CharacterName,
                                    TribeName         = demoMode?.GetTribeName() ?? extra?.player?.Tribe?.Name,
                                    DiscordName       = demoMode != null ? null : extra?.discordName,
                                    TimeOnline        = player.Time.ToStringCustom(),
                                    TimeOnlineSeconds = (int)Math.Round(player.Time.TotalSeconds)
                                });

                                n++;
                            }
                        }
                    }
                }
                else
                {
                    sr.OnlinePlayers = null;
                }

                result.Servers.Add(sr);
                //}
            }

            foreach (var context in _contextManager.Clusters)
            {
                var cc = new ClusterStatusViewModel
                {
                    Key        = context.Config.Key,
                    ServerKeys = _contextManager.Servers
                                 .Where(x => x.Config.ClusterKey.Equals(context.Config.Key, StringComparison.OrdinalIgnoreCase))
                                 .Select(x => x.Config.Key).ToArray()
                };
                result.Clusters.Add(cc);
            }

            return(result);
        }
Esempio n. 6
0
        // GET: RoutingSatus
        public ActionResult Index()
        {
            var nullRecord = _serverPerformanceService.Find(s => s.Province == null || s.Isp == null);

            var allData = _serverPerformanceService.GetAll();

            if (nullRecord.Any())
            {
                foreach (var delete in nullRecord)
                {
                    _serverPerformanceService.Remove(delete.Id);
                }
                DataForAnalysisService _dataForAnalysisService = new DataForAnalysisService();
                var data = _dataForAnalysisService.Find(s => s.Province == null || s.Isp == null);
                if (data.Any())
                {
                    foreach (var dat in data)
                    {
                        _dataForAnalysisService.Remove(dat.Id);
                    }
                }
                SummarizedDataService _summarizedDataService = new SummarizedDataService();
                var summarized = _summarizedDataService.Find(s => s.Province == null || s.Isp == null);
                if (summarized.Any())
                {
                    foreach (var sum in summarized)
                    {
                        _summarizedDataService.Remove(sum.Id);
                    }
                }
            }
            var allResult = allData.Where(s => !string.IsNullOrEmpty(s.Province)).OrderByDescending(p => p.ModifyDate);

            string[] province = new string[4] {
                "Beijing", "Chongqing", "Guangdong", "Huzhou"
            };
            string[] isp = new string[3] {
                "Telecom", "Mobile", "Unicom"
            };

            var returnList = new List <ServerStatusViewModel>();

            for (var i = 0; i < province.Count(); i++)
            {
                for (var p = 0; p < isp.Count(); p++)
                {
                    var lastData = allResult.FirstOrDefault(s => s.Province.Equals(province[i]) && s.Isp.Equals(isp[p]));
                    if (lastData != null)
                    {
                        var serverStatus = new ServerStatusViewModel()
                        {
                            Province      = province[i],
                            Isp           = isp[p],
                            LastExecution = lastData.ModifyDate.Value.ToLocalTime(),
                            Status        = lastData.ModifyDate.Value > DateTime.UtcNow.AddMinutes(-5) ? "Success" : "Failed"
                        };
                        returnList.Add(serverStatus);
                    }
                    else
                    {
                        var serverStatus = new ServerStatusViewModel()
                        {
                            Province      = province[i],
                            Isp           = isp[p],
                            LastExecution = new DateTime(1970, 1, 1, 0, 0, 0),
                            Status        = "Failed"
                        };
                        returnList.Add(serverStatus);
                    }
                }
            }

            return(View(returnList.OrderBy(s => s.Province).ThenBy(p => p.Status).ToList()));
        }
 public QuickConnectCommand(ServerStatusViewModel vm)
 {
     VM = vm;
 }
Esempio n. 8
0
        public async Task <ServerStatusAllViewModel> Get()
        {
            var demoMode = IsDemoMode() ? new DemoMode() : null;

            var anonymize = _config.AnonymizeWebApiData;
            var user      = WebApiHelper.GetUser(HttpContext, _config);

            if (anonymize)
            {
                var serverContext = _contextManager?.Servers?.FirstOrDefault();
                var player        = serverContext?.Players?.Where(x =>
                                                                  x.Tribe != null && x.Tribe.Creatures != null && x.Tribe.Structures != null &&
                                                                  x.Tribe.Creatures.Any(y => y.IsBaby) &&
                                                                  x.Tribe.Structures.OfType <ArkStructureCropPlot>().Any() &&
                                                                  x.Tribe.Structures.OfType <ArkStructureElectricGenerator>().Any()
                                                                  ).OrderByDescending(x => x.Creatures.Length).FirstOrDefault();

                if (player == null)
                {
                    user = null;
                }
                else
                {
                    user.Name    = player.Name;
                    user.SteamId = player.SteamId;
                    user.Roles   = _config?.WebApp?.AccessControl?.SelectMany(x => x.Value.Values)
                                   .SelectMany(x => x)
                                   .Distinct(StringComparer.OrdinalIgnoreCase)
                                   .OrderBy(x => x)
                                   .ToArray();
                }
            }

            var result = new ServerStatusAllViewModel {
                User = user, AccessControl = BuildViewModelForAccessControl(_config)
            };

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

            if (_contextManager.Servers != null)
            {
                foreach (var context in _contextManager.Servers)
                {
                    var serverContext = _contextManager.GetServer(context.Config.Key);

                    var tamedDinosCount    = context.TamedCreatures?.Count();
                    var uploadedDinosCount = context.CloudCreatures?.Count();
                    var wildDinosCount     = context.WildCreatures?.Count();
                    var structuresCount    = context.Structures?.Count();
                    var totalPlayers       = context.Players?.Count();
                    var totalTribes        = context.Tribes?.Count();
                    var serverStarted      = _serverService.GetServerStartTime(context.Config.Key);

                    var nextUpdate       = context.ApproxTimeUntilNextUpdate;
                    var nextUpdateTmp    = nextUpdate?.ToStringCustom();
                    var nextUpdateString = nextUpdate.HasValue ? !string.IsNullOrWhiteSpace(nextUpdateTmp) ? $"~{nextUpdateTmp}" : "waiting for new update ..." : null;
                    var lastUpdate       = context.LastUpdate;
                    var lastUpdateString = lastUpdate.ToStringWithRelativeDay();

                    var anonymizedServer      = anonymize ? _anonymizeData.GetServer(context.Config.Key) : null;
                    var serverStatusViewModel = new ServerStatusViewModel
                    {
                        Key                = anonymizedServer?.Key ?? context.Config.Key,
                        Name               = anonymizedServer?.Name ?? context.Data.ServerInfo?.ServerName,
                        Address            = anonymizedServer?.Address ?? context.Config.DisplayAddress ?? context.Data.ServerInfo?.Address,
                        Version            = context.Data.ServerInfo != null ? $"{context.Data.ServerInfo.MajorVersion}.{context.Data.ServerInfo.MinorVersion}" : null,
                        OnlinePlayerMax    = context.Data.ServerInfo?.MaxPlayers ?? 0,
                        MapName            = context.Data.ServerInfo?.MapName,
                        InGameTime         = context.Data.ServerInfo?.DayNumber.ToString(),
                        TamedCreatureCount = tamedDinosCount ?? 0,
                        CloudCreatureCount = uploadedDinosCount ?? 0,
                        WildCreatureCount  = wildDinosCount ?? 0,
                        StructureCount     = structuresCount ?? 0,
                        TribeCount         = totalTribes ?? 0,
                        LastUpdate         = lastUpdateString,
                        NextUpdate         = nextUpdateString,
                        ServerStarted      = serverStarted
                    };

                    result.Servers.Add(serverStatusViewModel);
                }
            }


            if (_contextManager.Clusters != null)
            {
                foreach (var context in _contextManager.Clusters)
                {
                    var cc = new ClusterStatusViewModel
                    {
                        Key        = context?.Config?.Key,
                        ServerKeys = _contextManager.Servers
                                     .Where(x => x.Config != null && x.Config.ClusterKey != null && x.Config.ClusterKey.Equals(context.Config.Key, StringComparison.OrdinalIgnoreCase))
                                     .Select(x => x.Config.Key).ToArray()
                    };
                    result.Clusters.Add(cc);
                }
            }

            return(result);
        }