Ejemplo n.º 1
0
        private void ReadNewLines(string path)
        {
            if (!filePositions.ContainsKey(path))
            {
                filePositions.Add(path, 0);
            }

            var openException = Util.Try(() => {
                using (Stream stream = File.Open(path, FileMode.Open))
                {
                    stream.Seek(filePositions[path], 0);
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        while (!reader.EndOfStream)
                        {
                            var e = Util.Try(() => logLinesQueue.Enqueue(reader.ReadLine()));
                            if (e != null)
                            {
                                Log.WriteError("Error reading line from {0} {1}", path, e.Message);
                            }
                        }
                        if (reader.BaseStream != null && reader.BaseStream.Position >= 0)
                        {
                            AddFileOffset(path, reader.BaseStream.Position);
                        }
                    }
                }
            });

            if (openException != null)
            {
                Log.WriteError("Can't open a file {0} {1}", path, openException.Message);
            }
        }
Ejemplo n.º 2
0
 public void Backup()
 {
     var original = String.Concat(configFilePath);
     var backup = String.Concat(configFilePath, ".bak");
     if (!File.Exists(backup) && File.Exists(original))
         Util.Try(() => File.Copy(original, backup, true));
 }
Ejemplo n.º 3
0
        public void ReadConfig()
        {
            if (string.IsNullOrWhiteSpace(this.configFilePath) || !File.Exists(this.configFilePath))
            {
                this.IsConfigReady = false;
                return;
            }

            Util.Try(() => {
                this.configContent = File.ReadAllText(this.configFilePath);

                this.GameRootFolder = Directory.GetParent(Path.GetDirectoryName(this.configFilePath)).FullName;

                this.MissionTextLogFolder = this.BuildDataFolder(this.GetString("text_log_folder"));
                this.ChatLogFolder        = this.BuildDataFolder(this.GetString("chatlog_folder"));

                this.IsMissionTextLogEnabled = this.GetBool("chatlog");
                this.IsChatLogEnabled        = this.GetBool("mission_text_log");
                this.AccountLogin            = this.GetString("login");
                this.AccountPassword         = this.GetString("password");

                this.RconLogin     = this.GetString("rcon_login");
                this.RconPassword  = this.GetString("rcon_password");
                this.IsRconEnabled = this.GetBool("rcon_start");
                this.RconIP        = this.GetIPAddress("rcon_ip");
                this.RconPort      = this.GetInt("rcon_port");
                this.IsConfigReady = true;
            });
        }
Ejemplo n.º 4
0
        private Exception Try(Action action)
        {
            if (action == null)
            {
                return(new NullReferenceException());
            }

            var error = Util.Try(action, false);

            if (error?.InnerException != null)
            {
                var mysqlError = error.InnerException as MySqlException;
                if (mysqlError == null)
                {
                    this.IsConfigIncorrect = true;
                    return(error);
                }

                var errorCodes = new int[] { 1049, 1042, 1044, 1045, 1046 };
                if (errorCodes.Contains(mysqlError.Number))
                {
                    this.IsConfigIncorrect = true;
                }
            }

            return(error);
        }
Ejemplo n.º 5
0
 private void Disconnect()
 {
     if (connection != null)
     {
         Util.Try(() => netStream.Close());
         Util.Try(() => connection.Close());
     }
 }
Ejemplo n.º 6
0
		private void DisposeScriptAssembly(string fileName)
		{
			var asm = this.loadedScripts.FirstOrDefault(script => script.Path.Equals(fileName, StringComparison.InvariantCultureIgnoreCase))?.AsmHelper;
										
			if (asm != null) {
				this.loadedScripts.RemoveAll(s => s.Path.Equals(fileName, StringComparison.InvariantCultureIgnoreCase));
				Util.Try(() => asm.Dispose());
			}
		}
Ejemplo n.º 7
0
 public void Stop()
 {
     dserverProcMonitor.Stop();
     foreach (var server in Servers)
     {
         Util.Try(() => server.Rcon.Stop());
         server.MissionLogService.Stop();
     }
 }
Ejemplo n.º 8
0
        public void Stop()
        {
            this.dserverProcMonitor.Stop();
            foreach (var server in this.Servers)
            {
                Util.Try(() => server.Rcon.Stop());
                server.MissionLogService.Stop();
            }

            this.IsRunning = false;
        }
Ejemplo n.º 9
0
        private void SetValue(string section, string name, string value)
        {
            var sectionContent = Re.GetSubString(configContent, String.Format(reSection,section));
            if (String.IsNullOrWhiteSpace(sectionContent))
                return;

            var replacement = Regex.Replace(sectionContent, String.Concat(@"[\s|\t]*",name, reParameter), Environment.NewLine);
            replacement = String.Concat(replacement, String.Format("{2}\t{0} = {1}", name, value, Environment.NewLine));
            configContent = configContent.Replace(sectionContent, replacement);

            Util.Try(() => File.WriteAllText(configFilePath, configContent));
        }
Ejemplo n.º 10
0
 private void Connect()
 {
     if (Config.RconIP != null &&
         Config.RconPort >= 1 ||
         Config.RconPort <= 65535)
     {
         Task.Factory.StartNew(() => {
             Util.Try(() => {
                 connection = new TcpClient(Config.RconIP.ToString(), Config.RconPort);
                 netStream  = connection.GetStream();
             }, false);
             IsConnected = true;
         }).Wait(2000);
     }
 }
Ejemplo n.º 11
0
 private void RemoveServer(int processId)
 {
     lock ( lockDservers )
     {
         var server = Servers.FirstOrDefault(ds => ds != null && ds.Process != null && ds.Process.Id == processId);
         if (server != null)
         {
             server.MissionLogService.Stop();
             Util.Try(() => server.Rcon.Stop());
             UI.Dispatch(() => {
                 Servers.Remove(server);
                 dserverProcMonitor.Remove(processId);
             });
         }
     }
 }
Ejemplo n.º 12
0
        private void SetValue(string section, string name, string value)
        {
            var sectionContent = Re.GetSubString(this.configContent, string.Format(RE_SECTION, section));

            if (string.IsNullOrWhiteSpace(sectionContent))
            {
                return;
            }

            var replacement = Regex.Replace(sectionContent, string.Concat(@"[\s|\t]*", name, RE_PARAMETER),
                                            Environment.NewLine);

            replacement        = string.Concat(replacement, string.Format("{2}\t{0} = {1}", name, value, Environment.NewLine));
            this.configContent = this.configContent.Replace(sectionContent, replacement);

            Util.Try(() => File.WriteAllText(this.configFilePath, this.configContent));
        }
Ejemplo n.º 13
0
        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            var path = e.FullPath;

            CurrentFileName = path;
            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                if (OnFileCreation != null)
                {
                    OnFileCreation(e.FullPath);
                }
            }
            if (e.ChangeType != WatcherChangeTypes.Deleted)
            {
                if (Preprocess != null)
                {
                    bool handled = false;
                    Util.Try(() => handled = Preprocess(File.ReadAllText(path)));
                    if (handled)
                    {
                        return;
                    }
                }
            }

            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                if (OnChanged != null)
                {
                    OnChanged(e.FullPath);
                }
                if (OnNewLine != null)
                {
                    ReadNewLines(e.FullPath);
                    string line = null;
                    while (logLinesQueue.TryDequeue(out line))
                    {
                        OnNewLine(line);
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public void LoadScripts()
        {
            string folder = AppDomain.CurrentDomain.GetData("DataDirectory") + scriptsSubFolder;

            if (!Directory.Exists(folder))
            {
                folder = @".\Scripts\";
            }

            var scriptFiles = Directory.GetFiles(folder, "*.cs", SearchOption.AllDirectories);

            config.ScriptConfigs.RemoveAll(script =>
                                           !scriptFiles.Contains(script.FileName) &&
                                           !scriptFiles.Contains(Path.Combine(folder, script.FileName)));

            foreach (var scriptPath in scriptFiles)
            {
                var scriptFileName = Path.GetFileName(scriptPath);
                Util.Try(() => {
                    LoadScript(scriptPath);
                });
            }
            tracker           = new TextFileTracker(folder, "*.cs");
            tracker.OnChanged = (fileName) =>
            {
                Util.Try(() =>
                {
                    Thread.Sleep(1000);
                    LoadScript(fileName);
                });
            };
            tracker.OnFileCreation = (fileName) =>
            {
                Util.Try(() =>
                {
                    Thread.Sleep(1000);
                    LoadScript(fileName);
                });
            };

            tracker.Start();
        }
Ejemplo n.º 15
0
        public void ReadConfig()
        {
            if (String.IsNullOrWhiteSpace(configFilePath) ||
                !File.Exists(configFilePath))
                return;

            Util.Try(() => {
                configContent = File.ReadAllText(configFilePath);

                GameRootFolder = Directory.GetParent(Path.GetDirectoryName(configFilePath)).FullName;
                
                MissionTextLogFolder = BuildDataFolder( GetString( "text_log_folder" ));
                ChatLogFolder = BuildDataFolder( GetString("chatlog_folder"));

                IsMissionTextLogEnabled = GetBool("chatlog");
                IsChatLogEnabled = GetBool("mission_text_log");
                Login = GetString("login");
                Password = GetString("password");
                IsRconEnabled = GetBool("rcon_start");
                RconIP = GetIPAddress("rcon_ip");
                RconPort = GetInt("rcon_port");
            });
        }
Ejemplo n.º 16
0
		public void LoadScripts()
		{
			var folder = AppDomain.CurrentDomain.GetData("DataDirectory") + SCRIPTS_SUB_FOLDER;
			if (!Directory.Exists(folder)) {
				folder = @".\Scripts\";
			}

			var scriptFiles = Directory.GetFiles(folder, "*.cs", SearchOption.AllDirectories)
				.Where(path => !Path.GetFileName(path).StartsWith("."))
				.ToList();

			this.config.ScriptConfigs.RemoveAll(script =>
														!scriptFiles.Contains(script.FileName) &&
														!scriptFiles.Contains(Path.Combine(folder, script.FileName)));

			foreach (var scriptPath in scriptFiles) {
				var scriptFileName = Path.GetFileName(scriptPath);
				Util.Try(() => { this.LoadScript(scriptPath); });
			}

			this.tracker = new TextFileTracker(folder, "*.cs") {
				OnChanged = (fileName) => {
					Util.Try(() => {
						Thread.Sleep(1000);
						this.LoadScript(fileName);
					});
				},
				OnFileCreation = (fileName) => {
					Util.Try(() => {
						Thread.Sleep(1000);
						this.LoadScript(fileName);
					});
				}
			};

			this.tracker.Start();
		}
Ejemplo n.º 17
0
        private void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            var path = e.FullPath;

            this.CurrentFileName = path;
            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                this.OnFileCreation?.Invoke(e.FullPath);
            }

            if (e.ChangeType != WatcherChangeTypes.Deleted)
            {
                if (this.Preprocess != null)
                {
                    var handled = false;
                    Util.Try(() => handled = this.Preprocess(File.ReadAllText(path)));
                    if (handled)
                    {
                        return;
                    }
                }
            }

            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                this.OnChanged?.Invoke(e.FullPath);

                if (this.OnNewLine != null)
                {
                    this.ReadNewLines(e.FullPath);
                    while (this.logLinesQueue.TryDequeue(out var line))
                    {
                        this.OnNewLine(line);
                    }
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Send raw command to server
        /// </summary>
        /// <param name="line">command</param>
        /// <returns>NameValueCollection with parameter name/value pairs</returns>
        public NameValueCollection RawCommand(string line)
        {
            LastErrorDescription = "Communication error";

            if (isStopped)
            {
                return(new NameValueCollection());
            }

            if (netStream == null || !netStream.CanWrite)
            {
                Start();
            }

            lock (lockConnection)
            {
                if (netStream.CanWrite)
                {
                    Byte[] sendBytes = Encoding.UTF8.GetBytes(String.Concat(line));
                    Byte[] length    = BitConverter.GetBytes((ushort)(line.Length + 1));
                    Byte[] zero      = { 0 };
                    Byte[] packet    = length.Concat(sendBytes).Concat(zero).ToArray();
                    Util.Try(() => netStream.Write(packet, 0, packet.Length), false);
                }
                else
                {
                    Disconnect();
                    return(new NameValueCollection());
                }
            }
            var writeTask = Task.Factory.StartNew <NameValueCollection>((obj) =>
            {
                try
                {
                    lock (lockConnection)
                    {
                        var rcon = obj as RconConnection;
                        if (rcon == null ||
                            rcon.connection == null ||
                            rcon.netStream == null)
                        {
                            return(new NameValueCollection());
                        }

                        if (rcon.netStream.CanRead)
                        {
                            while (!rcon.netStream.DataAvailable)
                            {
                                Thread.Sleep(1);
                            }

                            if (rcon.connection.ReceiveBufferSize <= 0)
                            {
                                return(new NameValueCollection());
                            }

                            byte[] bytes = new byte[rcon.connection.ReceiveBufferSize];
                            Util.Try(() => rcon.netStream.Read(bytes, 0, (int)rcon.connection.ReceiveBufferSize), false);
                            UInt16 length   = BitConverter.ToUInt16(bytes.Take(2).ToArray(), 0);
                            string response = null;
                            if (length > 2)
                            {
                                response = Encoding.UTF8.GetString(bytes.Skip(2).Take((int)length - 1).ToArray());
                            }

                            if (!String.IsNullOrWhiteSpace(response))
                            {
                                var result = HttpUtility.ParseQueryString(response);
                                string errorText;
                                LastErrorDescription = String.Empty;

                                if (errorCodes.TryGetValue(result["STATUS"], out errorText))
                                {
                                    LastErrorDescription = errorText;
                                }

                                return(result);
                            }
                            else
                            {
                                return(new NameValueCollection());
                            }
                        }
                        else
                        {
                            rcon.Disconnect();
                            rcon.Start();
                        }
                        return(new NameValueCollection());
                    }
                }
                catch (Exception e)
                {
                    Log.WriteError("{0}\n{1}", e.Message, e.StackTrace);
                    return(new NameValueCollection());
                }
            }, this);

            if (writeTask.Wait(3000))
            {
                return(writeTask.Result);
            }
            else
            {
                return(new NameValueCollection());
            }
        }
Ejemplo n.º 19
0
        public void ReadMissionHistory(string firstMissionLogFile = null)
        {
            //missionReport(2015-02-25_11-43-53)[0].txt

            if (firstMissionLogFile == null)
            {
                firstMissionLogFile = Util.GetNewestFilePath(MissionLogFolder, "missionReport(*)[0].txt");
                if (String.IsNullOrWhiteSpace(firstMissionLogFile))
                {
                    Log.WriteError("Mission log not found in {0}", MissionLogFolder);
                    return;
                }
            }
            else
            {
                firstMissionLogFile = this.With(x => Re.GetSubString(firstMissionLogFile, @"(missionReport\([\d+|\-|_]+\))\[\d+\].txt"))
                                      .With(x => String.Concat(x, "[0].txt"));
            }


            if (String.IsNullOrWhiteSpace(firstMissionLogFile))
            {
                Log.WriteError("Malformed log filename {0}", firstMissionLogFile);
                return;
            }

            Log.WriteInfo("Reading events history from {0}", firstMissionLogFile);


            StartNewMission(firstMissionLogFile);

            if (MissionStartDateTime.Equals(default(DateTime)))
            {
                return;
            }


            var missionFiles = Util.GetFilesSortedByTime(MissionLogFolder, String.Format("missionReport({0})[*].txt", missionDateTimePrefix), true);

            var readException = Util.Try(() => {
                foreach (var file in missionFiles)
                {
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.Length > 0 && !String.IsNullOrWhiteSpace(file))
                    {
                        if (tracker != null)
                        {
                            tracker.AddFileOffset(file, fileInfo.Length);
                        }

                        var lines = File.ReadAllLines(file);
                        if (lines != null)
                        {
                            foreach (var line in lines)
                            {
                                var data = MissionLogDataBuilder.GetData(line, MissionStartDateTime, GetCurrentEventNumber(), server);
                                if (data is MissionLogEventHeader)
                                {
                                    var header         = data as MissionLogEventHeader;
                                    header.MissionFile = Path.GetFileName(file);
                                    AddHistory(data);
                                }
                            }
                        }
                    }
                }
            });
        }