void tas_MyBattleMapChanged(object sender, OldNewPair <Battle> oldNewPair)
        {
            lastMapChange = DateTime.Now;

            Battle b = tas.MyBattle;

            if (b != null)
            {
                string mapName = b.MapName.ToLower();

                if (SpawnConfig == null)
                {
                    ComResetOptions(TasSayEventArgs.Default, new string[] { });
                    ComClearBox(TasSayEventArgs.Default, new string[] { });
                }

                try {
                    var    serv     = GlobalConst.GetSpringieService();
                    string commands = serv.GetMapCommands(mapName);
                    if (!string.IsNullOrEmpty(commands))
                    {
                        foreach (string c in commands.Split('\n').Where(x => !string.IsNullOrEmpty(x)))
                        {
                            RunCommand(c);
                        }
                    }
                } catch (Exception ex) {
                    Trace.TraceError("Error procesing map commands: {0}", ex);
                }
            }
        }
        void tas_BattleUserJoined(object sender, BattleUserEventArgs e1)
        {
            if (e1.BattleID != tas.MyBattleID)
            {
                return;
            }
            string name = e1.UserName;

            string welc = config.Welcome;

            if (!string.IsNullOrEmpty(welc))
            {
                welc = welc.Replace("%1", name);
                welc = welc.Replace("%2", GetUserLevel(name).ToString());
                welc = welc.Replace("%3", MainConfig.SpringieVersion);
                SayBattlePrivate(name, welc);
            }
            if (spring.IsRunning)
            {
                spring.AddUser(e1.UserName, e1.ScriptPassword);
                TimeSpan started = DateTime.Now.Subtract(spring.GameStarted);
                started = new TimeSpan((int)started.TotalHours, started.Minutes, started.Seconds);
                SayBattlePrivate(name, String.Format("THIS GAME IS CURRENTLY IN PROGRESS, PLEASE WAIT UNTIL IT ENDS! Running for {0}", started));
                SayBattlePrivate(name, "If you say !notify, I will message you when the current game ends.");
            }

            if (SpawnConfig == null)
            {
                try {
                    var serv             = GlobalConst.GetSpringieService();
                    PlayerJoinResult ret = serv.AutohostPlayerJoined(tas.MyBattle.GetContext(), tas.ExistingUsers[name].AccountID);
                    if (ret != null)
                    {
                        if (!string.IsNullOrEmpty(ret.PrivateMessage))
                        {
                            tas.Say(SayPlace.User, name, ret.PrivateMessage, false);
                        }
                        if (!string.IsNullOrEmpty(ret.PublicMessage))
                        {
                            tas.Say(SayPlace.Battle, "", ret.PublicMessage, true);
                        }
                        if (ret.ForceSpec)
                        {
                            tas.ForceSpectator(name);
                        }
                        if (ret.Kick)
                        {
                            tas.Kick(name);
                        }
                    }
                } catch (Exception ex) {
                    SayBattle("ServerManage error: " + ex, false);
                }
            }

            if (SpawnConfig != null && SpawnConfig.Owner == name) // owner joins, set him boss
            {
                ComBoss(TasSayEventArgs.Default, new[] { name });
            }
        }
 private static void RecordMissionResult(Spring spring, Mod modInfo)
 {
     if (spring.Context.GameEndedOk && !spring.Context.IsCheating)
     {
         Trace.TraceInformation("Submitting score for mission " + modInfo.Name);
         try
         {
             var service = GlobalConst.GetContentService();
             Task.Factory.StartNew(() =>
             {
                 try
                 {
                     service.SubmitMissionScore(Program.Conf.LobbyPlayerName,
                                                ZkData.Utils.HashLobbyPassword(Program.Conf.LobbyPlayerPassword),
                                                modInfo.Name,
                                                spring.Context.MissionScore ?? 0,
                                                spring.Context.MissionFrame / 30,
                                                spring.Context.MissionVars);
                 }
                 catch (Exception ex)
                 {
                     Trace.TraceError("Error sending score: {0}", ex);
                 }
             });
         }
         catch (Exception ex)
         {
             Trace.TraceError($"Error sending mission score: {ex}");
         }
     }
 }
        /// <summary>
        /// <description></description>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void onRegisterClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtName.Text) || string.IsNullOrEmpty(txtPassword.Text) || string.IsNullOrEmpty(txtDate.Text) || string.IsNullOrEmpty(checkboxText) || string.IsNullOrEmpty(selectedDesignation) || string.IsNullOrEmpty(encodedImgString))
                {
                    Snackbar.Make(txtUserName, GetString(Resource.String.require_all_Details), Snackbar.LengthLong).Show();
                    //GlobalConst.alertMessageBox(this, "Requir", "Please Enter All the Details..!!");
                }
                else
                {
                    EmployeeRegisterData employeeRegisterData = new EmployeeRegisterData()
                    {
                        imgUrl      = encodedImgString,
                        name        = txtName.Text,
                        userName    = txtUserName.Text,
                        password    = txtPassword.Text,
                        date        = txtDate.Text,
                        gender      = rdGender.Text,
                        hobbies     = checkboxText,
                        designation = selectedDesignation
                    };

                    GlobalConst.insertEmployee(employeeRegisterData);
                    Finish();
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, GetString(Resource.String.somthing_wrong), ToastLength.Short).Show();
            }
        }
Example #5
0
        public override string Arm(ServerBattle battle, Say e, string arguments = null)
        {
            var serv = GlobalConst.GetContentService(); // TODO this can be done directly, we are in server

            engines = serv.GetEngineList(null);
            if (!string.IsNullOrEmpty(arguments))
            {
                engines = engines.Where(x => x.Contains(arguments)).ToList();
            }
            return(String.Empty);
        }
Example #6
0
 private void UpdateSigma2()
 {
     if (sigma2.Count > 0)
     {
         sigma2[sigma2.Count - 1] = Math.Abs(days[sigma2.Count].day - days[sigma2.Count - 1].day) * GlobalConst.NaturalRatingVariancePerDay(days[sigma2.Count - 1].totalWeight) + GlobalConst.NaturalRatingVariancePerGame * (days[sigma2.Count].totalWeight - days[sigma2.Count - 1].totalWeight);
     }
     for (int i = sigma2.Count; i < days.Count - 1; i++)
     {
         sigma2.Add(Math.Abs(days[i + 1].day - days[i].day) * GlobalConst.NaturalRatingVariancePerDay(days[i].totalWeight) + GlobalConst.NaturalRatingVariancePerGame * (days[i + 1].totalWeight - days[i].totalWeight));
     }
 }
 private void HandleClicked(bool isClick)
 {
     if (isClick)
     {
         GlobalConst.deleteEmployee(n);
     }
     else
     {
         //TODO cancel button click
     }
 }
        private void DedicatedServerStarted(object sender, EventArgs e)
        {
            StopVote();

            if (HostedMod?.Mission != null)
            {
                var service = GlobalConst.GetContentService();
                foreach (var u in spring.LobbyStartContext.Players.Where(x => !x.IsSpectator))
                {
                    service.NotifyMissionRun(u.Name, HostedMod.Mission.Name);
                }
            }
        }
Example #9
0
 private string QueryDefaultEngine()
 {
     Status = "Querying default engine";
     try
     {
         return(GlobalConst.GetContentService().GetDefaultEngine());
     }
     catch (Exception ex)
     {
         Trace.TraceError("Querying default engine failed: {0}", ex);
         Status = "Querying default engine has failed";
     }
     return(null);
 }
Example #10
0
            public SendEmail()
            {
                // VBConversions Note: Non-static class variable initialization is below.  Class variables cannot be initially assigned non-static values in C#.
                _BCC          = new MailAddress(GlobalConst.get_AppSettings("email.info", "*****@*****.**"), "admin");
                _BodyEncoding = Encoding.Default;

                SmtpURL    = ConfigurationManager.AppSettings["smtp.server"];
                SmtpAcount = ConfigurationManager.AppSettings["smtp.acount"];
                SmtpCode   = ConfigurationManager.AppSettings["smtp.code"];
                DeliveryNotificationOptions = (int)DeliveryNotificationOptions.OnFailure + DeliveryNotificationOptions.OnSuccess;

                //"massmail.scannet.dk"
                //ConfigurationManager.AppSettings("adminrolename")
            }
Example #11
0
        void spring_SpringStarted(object sender, EventArgs e)
        {
            //lockedUntil = DateTime.MinValue;
            //tas.ChangeLock(false);
            if (hostedMod.IsMission)
            {
                var service = GlobalConst.GetContentService();
                foreach (UserBattleStatus u in tas.MyBattle.Users.Values.Where(x => !x.IsSpectator))
                {
                    service.NotifyMissionRun(u.Name, hostedMod.ShortName);
                }
            }

            StopVote();
        }
 public static void StartScriptMission(string name)
 {
     try
     {
         var serv = GlobalConst.GetContentService();
         SinglePlayerBar.DownloadAndStartMission(serv.GetScriptMissionData(name));
     }
     catch (WebException ex)
     {
         Trace.TraceWarning("Problem starting script mission {0}: {1}", name, ex);
     }
     catch (Exception ex)
     {
         Trace.TraceError("Error starting mission {0}: {1}", name, ex);
     }
 }
Example #13
0
        public SpringieServer()
        {
            var wc = GlobalConst.GetContentService();

            Task.Factory.StartNew(() => {
                try {
                    var res = wc.GetEloTop10();
                    for (var i = 0; i < res.Count; i++)
                    {
                        top10[res[i]] = i + 1;
                    }
                } catch (Exception ex) {
                    Trace.TraceError(ex.ToString());
                }
            });
        }
Example #14
0
 protected override void SuccessAction()
 {
     try {
         bool val;
         var  moves =
             tas.MyBattle.Users.Values.Where(x => x.Name != tas.MyBattle.Founder.Name)
             .Where(x => userVotes.TryGetValue(x.Name, out val) && val)
             .Select(x => new MovePlayerEntry()
         {
             BattleHost = host, PlayerName = x.Name
         })
             .ToList();    // move those that voted yes
         var serv = GlobalConst.GetSpringieService();
         serv.MovePlayers(tas.UserName, tas.UserPassword, moves);
     } catch (Exception ex) {
         ah.SayBattle(ex.ToString());
     }
 }
        public void StartScriptMission(string missionName)
        {
            var serv      = GlobalConst.GetContentService();
            var profile   = serv.GetScriptMissionData(missionName);
            var downloads = new List <Download>();

            downloads.Add(Program.Downloader.GetResource(DownloadType.RAPID, profile.ModName));
            downloads.Add(Program.Downloader.GetResource(DownloadType.MAP, profile.MapName));
            downloads.Add(Program.Downloader.GetResource(DownloadType.ENGINE, Program.TasClient.ServerWelcome.Engine ?? GlobalConst.DefaultEngineOverride));
            if (profile.ManualDependencies != null)
            {
                foreach (var entry in profile.ManualDependencies)
                {
                    if (!string.IsNullOrEmpty(entry))
                    {
                        downloads.Add(Program.Downloader.GetResource(DownloadType.NOTKNOWN, entry));
                    }
                }
            }

            downloads = downloads.Where(x => x != null).ToList();

            if (downloads.Count > 0)
            {
                var dd = new WaitDownloadDialog(downloads);
                if (dd.ShowDialog(Program.MainWindow) == DialogResult.Cancel)
                {
                    return;
                }
            }

            var spring = new Spring(Program.SpringPaths);
            var name   = Program.Conf.LobbyPlayerName;

            if (string.IsNullOrEmpty(name))
            {
                name = "Player";
            }

            spring.RunLocalScriptGame(
                profile.StartScript.Replace("%MOD%", profile.ModName).Replace("%MAP%", profile.MapName).Replace("%NAME%", name),
                Program.TasClient.ServerWelcome.Engine ?? GlobalConst.DefaultEngineOverride);
            serv.NotifyMissionRun(name, profile.Name);
        }
Example #16
0
        public CurrentLobbyStats GetCurrentStats()
        {
            var ret = new CurrentLobbyStats();

            foreach (var u in client.ExistingUsers.Values)
            {
                if (!u.IsBot && !u.IsInGame && !u.IsInBattleRoom)
                {
                    ret.UsersIdle++;
                }
            }

            foreach (var b in client.ExistingBattles.Values)
            {
                if (!GlobalConst.IsZkMod(b.ModName))
                {
                    continue;
                }
                foreach (var u in b.Users.Select(x => x.LobbyUser))
                {
                    if (u.IsBot)
                    {
                        continue;
                    }
                    if (u.IsInGame)
                    {
                        ret.UsersFighting++;
                    }
                    else if (u.IsInBattleRoom)
                    {
                        ret.UsersWaiting++;
                    }
                }
                if (b.IsInGame)
                {
                    ret.BattlesRunning++;
                }
                else
                {
                    ret.BattlesWaiting++;
                }
            }
            return(ret);
        }
Example #17
0
 private async Task Process(GetSpringBattleInfo args)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             var serv = GlobalConst.GetContentService();
             var sbi  = serv.GetSpringBattleInfo(args.GameID);
             SendCommand(new GetSpringBattleInfoDone()
             {
                 GameID           = args.GameID,
                 SpringBattleInfo = sbi
             });
         }
         catch (Exception ex)
         {
             Trace.TraceWarning("Error getting spring battle info {0} : {1}", args.GameID, ex);
         }
     });
 }
Example #18
0
        public static void StartDownloadedMission(ScriptMissionData profile, string modInternalName)
        {
            var spring = new Spring(Program.SpringPaths);
            var name   = Program.Conf.LobbyPlayerName;

            if (string.IsNullOrEmpty(name))
            {
                name = "Player";
            }

            if (Utils.VerifySpringInstalled())
            {
                spring.StartGame(Program.TasClient,
                                 null,
                                 null,
                                 profile.StartScript.Replace("%MOD%", modInternalName).Replace("%MAP%", profile.MapName).Replace("%NAME%", name), Program.Conf.UseSafeMode, Program.Conf.UseMtEngine);
                var serv = GlobalConst.GetContentService();
                serv.NotifyMissionRun(Program.Conf.LobbyPlayerName, profile.Name);
            }
        }
        private void DedicatedServerStarted(object sender, EventArgs e)
        {
            try
            {
                StopVote();

                if (HostedMod?.Mission != null)
                {
                    var service = GlobalConst.GetContentService();
                    foreach (var u in spring.LobbyStartContext.Players.Where(x => !x.IsSpectator))
                    {
                        service.NotifyMissionRun(u.Name, HostedMod.Mission.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error processing dedi server started: {0}", ex);
            }
        }
 public static bool UpdatePublicCommunityInfo(this PlasmaDownloader downloader, IChobbylaProgress progress)
 {
     try
     {
         progress.Status = "Loading community news";
         var folder = Path.Combine(downloader.SpringPaths.WritableDirectory, "news");
         if (!Directory.Exists(folder))
         {
             Directory.CreateDirectory(folder);
         }
         var info = GlobalConst.GetContentService().GetPublicCommunityInfo();
         File.WriteAllText(Path.Combine(folder, "community.json"), JsonConvert.SerializeObject(info));
         return(true);
     }
     catch (Exception ex)
     {
         Trace.TraceError("Loading public community info failed: {0}", ex);
         progress.Status = "Loading community news failed";
         return(false);
     }
 }
        static void SlaveStartSpring(AutoHost ah, List <UserBattleStatus> team)
        {
            var serv = GlobalConst.GetSpringieService();

            var context = ah.tas.MyBattle.GetContext();

            context.Players = team.Select(x => new PlayerTeam()
            {
                AllyID = x.AllyNumber, Name = x.Name, LobbyID = x.LobbyUser.AccountID, TeamID = x.TeamNumber, IsSpectator = false
            }).ToList();

            var balance = serv.BalanceTeams(context, true, null, null);

            ah.ApplyBalanceResults(balance);
            context.Players = balance.Players;
            context.Bots    = balance.Bots;

            ah.SayBattle("please wait, game is about to start");
            ah.StopVote();
            ah.slaveContextOverride = context;
            ah.tas.StartGame();
        }
Example #22
0
        //Register Buttton Click
        #region Registration
        /// <summary>
        /// <description></description>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void onRegisterButtonClick(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtFirstName.Text) || string.IsNullOrEmpty(txtLastName.Text) || string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text) || string.IsNullOrEmpty(txtConfPassword.Text) || string.IsNullOrEmpty(encodedImgString))
                {
                    Snackbar.Make(txtUserName, GetString(Resource.String.require_all_Details), Snackbar.LengthLong).Show();
                    //GlobalConst.alertMessageBox(this, "Requir", "Please Enter All the Details..!!");
                }
                else
                {
                    if (txtPassword.Text == txtConfPassword.Text)
                    {
                        RegisterData registerData = new RegisterData()
                        {
                            firstName       = txtFirstName.Text.Trim(),
                            lastName        = txtLastName.Text.Trim(),
                            userName        = txtUserName.Text.Trim(),
                            password        = txtPassword.Text.Trim(),
                            gender          = rdGender.Text.Trim(),
                            imgUrl          = encodedImgString,
                            currentLocation = current_Location
                        };

                        GlobalConst.insert(registerData);
                        Finish();
                    }
                    else
                    {
                        Toast.MakeText(this, GetString(Resource.String.conf_password), ToastLength.Long).Show();
                    }
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, GetString(Resource.String.somthing_wrong), ToastLength.Long).Show();
            }
        }
Example #23
0
        public override string Arm(ServerBattle battle, Say e, string arguments = null)
        {
            engine = string.IsNullOrEmpty(arguments) ? battle.server.Engine : arguments;

            if ((battle.Mode != AutohostMode.None || !battle.IsPassworded) && engine != battle.server.Engine)
            {
                battle.Respond(e, $"You cannot change engine to version other than {battle.server.Engine} here, use custom passworded room");
                return(null);
            }

            if (!battle.server.SpringPaths.HasEngineVersion(engine))
            {
                var serv = GlobalConst.GetContentService(); // TODO this can be done directly, we are in server
                if (!serv.GetEngineList(null).Any(x => x == engine))
                {
                    battle.Respond(e, "Engine not found");
                    return(null);
                }
                battle.server.Downloader.GetResource(DownloadType.ENGINE, engine);
            }

            return($"Change engine to {engine}?");
        }
Example #24
0
        public void UpdateAll()
        {
            try
            {
                var serv    = GlobalConst.GetSpringieService();
                var configs = serv.GetClusterConfigs(Config.ClusterNode);

                var copy = new List <AutoHost>();
                lock (autoHosts)
                {
                    copy = autoHosts.ToList();
                }
                foreach (var conf in configs)
                {
                    if (!copy.Any(x => x.config.Login == conf.Login))
                    {
                        SpawnAutoHost(conf, null).Start();
                    }
                    else
                    {
                        foreach (var ah in copy.Where(x => x.config.Login == conf.Login && x.SpawnConfig == null))
                        {
                            ah.config = conf;
                        }
                    }
                }
                var todel = copy.Where(x => !configs.Any(y => y.Login == x.config.Login)).ToList();
                foreach (var ah in todel)
                {
                    StopAutohost(ah);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error in periodic updates: {0}", ex);
            }
        }
 public static bool UpdateFeaturedCustomGameModes(this PlasmaDownloader downloader, IChobbylaProgress progress)
 {
     try
     {
         progress.Status = "Loading custom game modes";
         var folder = Path.Combine(downloader.SpringPaths.WritableDirectory, "CustomModes");
         if (!Directory.Exists(folder))
         {
             Directory.CreateDirectory(folder);
         }
         var modes = GlobalConst.GetContentService().GetFeaturedCustomGameModes();
         foreach (var mode in modes)
         {
             File.WriteAllText(Path.Combine(folder, $"{mode.FileName}.json"), mode.FileContent);
         }
         return(true);
     }
     catch (Exception ex)
     {
         Trace.TraceError("Loading custom game modes failed: {0}", ex);
         progress.Status = "Loading custom game modes failed";
         return(false);
     }
 }
Example #26
0
        public override void End()
        {
            bool val;

            try {
                var moves =
                    tas.MyBattle.Users.Values.Where(x => x.Name != tas.MyBattle.Founder.Name)
                    .Where(x => userVotes.TryGetValue(x.Name, out val) && val)
                    .Select(x => new MovePlayerEntry()
                {
                    BattleHost = host, PlayerName = x.Name
                })
                    .ToList();    // move those that voted yes if there are at least 2
                if (moves.Count > 1)
                {
                    var serv = GlobalConst.GetSpringieService();
                    serv.MovePlayers(tas.UserName, tas.UserPassword, moves);
                }
            } catch (Exception ex) {
                ah.SayBattle(ex.ToString());
            }

            base.End();
        }
        /// <summary>
        /// <description>Login</description>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void onLoginClicked(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPasword.Text))
                {
                    Snackbar.Make(txtUserName, GetString(Resource.String.require_all_Details), Snackbar.LengthLong).Show();
                    //GlobalConst.alertMessageBox(this, "Requir", "Please Enter All the Details..!!",HandleClicked);
                }
                else
                {
                    if (txtUserName.Text.Trim() == "Admin" && txtPasword.Text.Trim() == "admin")
                    {
                        if (checkRemeberMe.Checked)
                        {
                            UserSettings.UserName = txtUserName.Text;
                            UserSettings.Password = txtPasword.Text;
                            UserSettings.isLogin  = true;
                        }

                        var intent = new Intent(this, typeof(EmployeeListActivity));
                        StartActivity(intent);
                        Finish();
                        clear();
                    }
                    else
                    {
                        GlobalConst.alertMessageBox(this, "", "Invalid Username and Password", HandleClicked);
                    }
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, GetString(Resource.String.somthing_wrong), ToastLength.Short).Show();
            }
        }
        public static async Task <bool> UpdateMissions(this PlasmaDownloader downloader, IChobbylaProgress progress)
        {
            try
            {
                progress.Status = "Downloading missions";
                var missions = GlobalConst.GetContentService().GetDefaultMissions();

                var missionsFolder = Path.Combine(downloader.SpringPaths.WritableDirectory, "missions");
                if (!Directory.Exists(missionsFolder))
                {
                    Directory.CreateDirectory(missionsFolder);
                }
                var missionFile = Path.Combine(missionsFolder, "missions.json");

                List <ClientMissionInfo> existing = null;
                if (File.Exists(missionFile))
                {
                    try
                    {
                        existing = JsonConvert.DeserializeObject <List <ClientMissionInfo> >(File.ReadAllText(missionFile));
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceWarning("Error reading mission file {0} : {1}", missionFile, ex);
                    }
                }
                existing = existing ?? new List <ClientMissionInfo>();

                var toDownload =
                    missions.Where(
                        m => !existing.Any(x => (x.MissionID == m.MissionID) && (x.Revision == m.Revision) && (x.DownloadHandle == m.DownloadHandle)))
                    .ToList();

                // download mission files
                foreach (var m in toDownload)
                {
                    if (m.IsScriptMission && (m.Script != null))
                    {
                        m.Script = m.Script.Replace("%MAP%", m.Map);
                    }
                    if (!m.IsScriptMission)
                    {
                        if (!await downloader.DownloadFile("Downloading mission " + m.DisplayName, DownloadType.MISSION, m.DownloadHandle, progress).ConfigureAwait(false))
                        {
                            return(false);
                        }
                    }
                    if (!downloader.DownloadUrl("Downloading image", m.ImageUrl, Path.Combine(missionsFolder, $"{m.MissionID}.png"), progress))
                    {
                        return(false);
                    }
                }

                File.WriteAllText(missionFile, JsonConvert.SerializeObject(missions));

                return(true);
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error updating missions: {0}", ex);
                return(false);
            }
        }
Example #29
0
        private static ResourceInfo Register(UnitSync unitsync, ResourceInfo resource)
        {
            Trace.TraceInformation("UnitSyncer: registering {0}", resource.Name);
            ResourceInfo info = null;

            try
            {
                info = unitsync.GetResourceFromFileName(resource.ArchivePath);

                if (info != null)
                {
                    var serializedData = MetaDataCache.SerializeAndCompressMetaData(info);

                    var map     = info as Map;
                    var creator = new TorrentCreator();
                    creator.Path = resource.ArchivePath;
                    var ms = new MemoryStream();
                    creator.Create(ms);

                    byte[] minimap   = null;
                    byte[] metalMap  = null;
                    byte[] heightMap = null;
                    if (map != null)
                    {
                        minimap   = map.Minimap.ToBytes(ImageSize);
                        metalMap  = map.Metalmap.ToBytes(ImageSize);
                        heightMap = map.Heightmap.ToBytes(ImageSize);
                    }

                    var hash   = Hash.HashBytes(File.ReadAllBytes(resource.ArchivePath));
                    var length = new FileInfo(resource.ArchivePath).Length;

                    Trace.TraceInformation("UnitSyncer: uploading {0} to server", info.Name);

                    ReturnValue e;
                    try
                    {
                        var service = GlobalConst.GetContentService();
                        e = service.RegisterResource(PlasmaServiceVersion,
                                                     null,
                                                     hash.ToString(),
                                                     (int)length,
                                                     info.ResourceType,
                                                     resource.ArchiveName,
                                                     info.Name,
                                                     serializedData,
                                                     info.Dependencies,
                                                     minimap,
                                                     metalMap,
                                                     heightMap,
                                                     ms.ToArray());
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("UnitSyncer: Error uploading data to server: {0}", ex);
                        return(null);
                    }

                    if (e != ReturnValue.Ok)
                    {
                        Trace.TraceWarning("UnitSyncer: Resource registering failed: {0}", e);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error registering resource {0} : {1}", resource.ArchivePath, ex);
                return(null);
            }

            return(info);
        }
Example #30
0
        private void ParseInfolog(string text, bool isCrash)
        {
            if (string.IsNullOrEmpty(text))
            {
                Trace.TraceWarning("Infolog is empty");
                return;
            }
            try {
                var    hasError     = false;
                var    modName      = battleResult.Mod;
                var    mapName      = battleResult.Map;
                var    isCheating   = false;
                int?   score        = null;
                int    scoreFrame   = 0;
                string gameId       = null;
                string demoFileName = null;
                string missionVars  = "";

                foreach (var cycleline in text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var line      = cycleline;
                    var gameframe = 0;
                    if (line.StartsWith("[DedicatedServer]"))
                    {
                        line = line.Replace("[DedicatedServer] ", "");
                    }

                    if (line.StartsWith("["))
                    {
                        var idx = line.IndexOf("] ");
                        if (idx > 0)
                        {
                            int.TryParse(line.Substring(1, idx - 1), out gameframe);
                            if (idx >= 0)
                            {
                                line = line.Substring(idx + 2);
                            }
                        }
                    }

                    // FIXME: why are these even null in the first place?
                    if (mapName == null && line.StartsWith("Using map"))
                    {
                        mapName = line.Substring(10).Trim();
                    }

                    if (modName == null && line.StartsWith("Using game"))
                    {
                        modName = line.Substring(11).Trim();
                    }

                    if (line.StartsWith("recording demo"))
                    {
                        demoFileName = Path.GetFileName(line.Substring(15).Trim());                                     // 91.0
                    }
                    else if (line.StartsWith("[DedicatedServer] recording demo"))
                    {
                        demoFileName = Path.GetFileName(line.Substring(33).Trim());                                                              // 95.0 and later
                    }
                    if (line.StartsWith("Using demofile"))
                    {
                        return;                                    // do nothing if its demo
                    }
                    if (line.StartsWith("GameID: ") && gameId == null)
                    {
                        gameId = line.Substring(8).Trim();
                    }

                    if (line.StartsWith("STATS:"))
                    {
                        statsData.Add(line.Substring(6));
                    }

                    if (line.Contains("SCORE: ") && !isCheating && battleResult.IsMission)
                    {
                        var match = Regex.Match(line, "SCORE: ([^ ]+)");
                        if (match.Success)
                        {
                            // game score
                            var data = match.Groups[1].Value;
                            //Trace.TraceInformation("Score data (raw) : " + data);
                            data = Encoding.ASCII.GetString(Convert.FromBase64String(match.Groups[1].Value));
                            //Trace.TraceInformation("Score data (decoded) : " + data);
                            var parts = data.Split('/');
                            score = 0;
                            if (parts.Length > 1)
                            {
                                score     = Convert.ToInt32(parts[1]);
                                gameframe = Convert.ToInt32(parts[0]);
                            }
                            else
                            {
                                score = Convert.ToInt32(data);
                            }

                            scoreFrame = gameframe;
                        }
                    }
                    if (line.Contains("MISSIONVARS:") && battleResult.IsMission)
                    {
                        var match = Regex.Match(line, "MISSIONVARS: ([^ ]+)");
                        missionVars = match.Groups[1].Value.Trim();
                        Trace.TraceInformation(string.Format("Mission variables: {0} (original line: {1})", missionVars, line));
                    }

                    // obsolete, hanlded by pm messages
                    //if (line.StartsWith("STATS:")) statsData.Add(line.Substring(6));

                    if (line.StartsWith("Cheating!") || line.StartsWith("Cheating is enabled!"))
                    {
                        isCheating = true;
                    }

                    if (line.StartsWith("Error") || line.StartsWith("LuaRules") || line.StartsWith("Internal error") || line.StartsWith("LuaCOB") ||
                        (line.StartsWith("Failed to load") && !line.Contains("duplicate name")))
                    {
                        hasError = true;
                    }
                }
                if (score != null || !String.IsNullOrEmpty(missionVars))
                {
                    Trace.TraceInformation("Submitting score for mission " + modName);
                    try {
                        using (var service = new ContentService {
                            Proxy = null
                        }) {
                            service.SubmitMissionScoreCompleted += (s, e) =>
                            {
                                if (e.Error != null)
                                {
                                    if (e.Error is WebException)
                                    {
                                        Trace.TraceWarning("Error sending score: {0}", e.Error);
                                    }
                                    else
                                    {
                                        Trace.TraceError("Error sending score: {0}", e.Error);
                                    }
                                }
                            };
                            service.SubmitMissionScoreAsync(lobbyUserName, Utils.HashLobbyPassword(lobbyPassword), modName, score ?? 0, scoreFrame / 30, missionVars);
                        }
                    } catch (Exception ex) {
                        Trace.TraceError(string.Format("Error sending mission score: {0}", ex));
                    }
                }

                var modOk = GlobalConst.IsZkMod(modName);

                // submit main stats
                if (!isCheating && !isCrash && modOk && gameEndedOk)
                {
                    if (isHosting)
                    {
                        var service = new SpringieService()
                        {
                            Proxy = null
                        };
                        var mis = new ContentService()
                        {
                            Proxy = null
                        };
                        try {
                            battleResult.EngineBattleID = gameId;
                            battleResult.ReplayName     = demoFileName;

                            // set victory team for all allied with currently alive
                            foreach (var p in statsPlayers.Values.Where(x => !x.IsSpectator && x.LoseTime == null))
                            {
                                foreach (var q in statsPlayers.Values.Where(x => !x.IsSpectator && x.AllyNumber == p.AllyNumber))
                                {
                                    q.IsVictoryTeam = true;
                                }
                            }

                            if (StartContext != null)
                            {
                                var result = service.SubmitSpringBattleResult(StartContext, lobbyPassword, battleResult, Enumerable.ToArray(statsPlayers.Values), statsData.ToArray());
                                if (result != null)
                                {
                                    foreach (var line in result.Split('\n'))
                                    {
                                        client.Say(TasClient.SayPlace.Battle, "", line, true);
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            Trace.TraceError("Error sending game result: {0}", ex);
                        }
                    }

                    if (statsData.Count > 1)
                    {
                        // must be more than 1 line - 1 is player list
                        var statsService = new StatsCollector {
                            Proxy = null
                        };
                        try {
                            statsService.SubmitGameEx(gameId, modName, mapName, statsData.ToArray());
                        } catch (Exception ex) {
                            Trace.TraceError("Error sending game stats: {0}", ex);
                        }
                    }
                }
            } catch (Exception ex) {
                Trace.TraceError("Error processing spring log: {0}", ex);
            }
        }