Ejemplo n.º 1
0
 public bool Stop()
 {
     _kernel.Release();//todo:::此处释放服务
     _webServer.Stop();
     UpdateMessage?.Invoke("http://" + Config.PublishHost + ":" + Config.PublishPort + "/Radio 人为停止!");
     return(true);
 }
Ejemplo n.º 2
0
 public bool Start()
 {
     ReadConfig();
     _webServer            = new AsyncHttpServer(Config.PublishHost, int.Parse(Config.PublishPort));
     _webServer.OnGetData += WebServer_OnGetData;
     _webServer.Start();
     UpdateMessage?.Invoke("http://" + Config.PublishHost + ":" + Config.PublishPort + "/Radio 网络服务启动。");
     _kernel = new Kernel(Config);
     _kernel.Init();//todo:::此处初始化服务
     return(true);
 }
Ejemplo n.º 3
0
        public void ComputerPlay()
        {
            if (backgroundSearchTask != null && backgroundSearchTask.Status == TaskStatus.Running)
            {
                UpdateMessage?.Invoke("stop thinking...");
                backgroundSearchTokenSource.Cancel();
            }

            Busy = true;
            UpdateMessage?.Invoke("searching...");

            Engine.UpdateProgress = r => UpdateResult?.Invoke(r);

            var          bb     = Board.ToBitBoard();
            var          depth  = GetSearchDepth();
            SearchResult result = null;

            if (Board.LastMove != null)
            {
                if (moveMaps.ContainsKey(Board.LastMove.Value))
                {
                    var item = moveMaps[Board.LastMove.Value];
                    if (Board.ValidMove(item.Move))
                    {
                        result = new SearchResult
                        {
                            Move    = item.Move,
                            Score   = item.Eval,
                            Process = 1,
                            Message = "BackgroundSearch",
                        };
                    }
                }
            }

            if (result == null)
            {
                result = Engine.Search(bb, depth);

                if (result.IsTimeout)
                {
                    //timeout, random move
                    var moves = Board.FindMoves();
                    result.Move = moves[new Random().Next(0, moves.Length)];
                }
            }

            PlayerPlay(result.Move);
            UpdatePlay?.Invoke(PlayerType.Computer, result.Move);
            UpdateResult?.Invoke(result);

            // if (bb.EmptyPiecesCount() > EdaxEngine.WinLoseDepth)
            if (!Board.CanMove())
            {
                moveMaps.Clear();
            }
            else
            {
                if (backgroundSearchTask != null)
                {
                    var i = 0;
                    while (i++ < 100)
                    {
                        if (backgroundSearchTask.Status != TaskStatus.Running)
                        {
                            break;
                        }

                        UpdateMessage?.Invoke($"wait times: {i++}...");
                        Thread.Sleep(100);
                    }
                    UpdateMessage?.Invoke("thinking was stoped.");
                }

                backgroundSearchTokenSource = new CancellationTokenSource();
                backgroundSearchTask        = BackgroundSearch(backgroundSearchTokenSource.Token);
            }

            Busy = false;
        }
Ejemplo n.º 4
0
 private void OnUpdateMessage(Updates update)
 {
     UpdateMessage?.Invoke(this, update);
 }
Ejemplo n.º 5
0
        // upload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;

        #endregion

        #region Help

        // help.getConfig#c4f9186b = Config;
        // help.getNearestDc#1fb33026 = NearestDc;
        // help.getAppUpdate#c812ac7e device_model:string system_version:string app_version:string lang_code:string = help.AppUpdate;
        // help.saveAppLog#6f02f748 events:Vector<InputAppEvent> = Bool;
        // help.getInviteText#a4a95186 lang_code:string = help.InviteText;
        // help.getSupport#9cdf08cd = help.Support;

        #endregion

        private void OnUpdateMessage(object sender, Updates e)
        {
            UpdateMessage?.Invoke(this, e);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Invoke the UpdateMessage event; called whenever a message is
 /// updated.
 /// </summary>
 /// <param name="message">
 /// The updated message.
 /// </param>
 protected virtual void OnUpdateMessage(string message)
 {
     UpdateMessage?.Invoke(this, message);
 }
Ejemplo n.º 7
0
 protected virtual void OnUpdateMessage(object sender, TLAbsUpdates e)
 {
     UpdateMessage?.Invoke(this, e);
 }
Ejemplo n.º 8
0
 private void OnUpdateMessage(TeleSharp.TL.TLAbsUpdates updates)
 {
     UpdateMessage?.Invoke(this, updates);
 }
Ejemplo n.º 9
0
        public async Task <bool> UpdateServer(Server server)
        {
            var serverPath = new DirectoryInfo(server.Path);

            if (!serverPath.Exists)
            {
                serverPath.Create();
            }

            using (var scope = _serviceScopeFactory.CreateScope())
                using (var db = scope.ServiceProvider.GetRequiredService <MonitorDBContext>())
                {
                    var scopedServices = scope.ServiceProvider;

                    StringBuilder outputStringBuilder = new StringBuilder();

                    // Params stuff
                    List <string[]> parameterBuilder = new List <string[]>
                    {
                        new string[] { "+login", "anonymous" },                 // TODO: Allow user logins
                        new string[] { "+force_install_dir", $"\"{serverPath.FullName}\"" }
                    };

                    // F*****g dynamic shit param builder what the f**k
                    List <string> updateText = new List <string>
                    {
                        server.Game.SteamID?.ToString(CultureInfo.InvariantCulture)
                    };
                    if (!String.IsNullOrEmpty(server.Branch) && server.Branch != "public")
                    {
                        updateText.Add("-beta");
                        updateText.Add(server.Branch);
                        if (!String.IsNullOrEmpty(server.BranchPassword))
                        {
                            updateText.Add("-betapassword");
                            updateText.Add(server.BranchPassword);
                        }

                        // TODO: Should add 'validate' param?
                    }

                    // app_update param builder
                    StringBuilder updateParams = new StringBuilder();
                    if (updateText.Count > 1)
                    {
                        updateParams.Append("\"");
                    }
                    updateParams.Append(String.Join(" ", updateText));
                    if (updateText.Count > 1)
                    {
                        updateParams.Append("\"");
                    }

                    parameterBuilder.Add(new string[] { "+app_update", updateParams.ToString() });

                    parameterBuilder.Add(new string[] { "+quit" });

                    string steamCMDArguments = String.Join(" ", parameterBuilder.Select(param => String.Join(" ", param)).ToArray());


                    _logger.LogInformation("Starting SteamCMD with arguments: {0}", steamCMDArguments);


                    // Init proccess listeners

                    IPtyConnection steamCMDProc = null;

                    var         downloadProgressRegex = @"Update state \((.+?)\) downloading, progress: ([\d.]+) \((\d*) \/ (\d*)\)";
                    CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                    ci.NumberFormat.CurrencyDecimalSeparator = ".";

                    //DataReceivedEventHandler outputEventHandler = (sender, e) =>
                    EventHandler outputEventHandler = (sender, e2) =>
                    {
                        var e = (CustomDataReceivedEventArgs)e2;
                        _logger.LogDebug("SteamCMD Log {0} - {1}: {2}", server.Id, steamCMDProc.Pid, e.Data);

                        UpdateMessage?.Invoke(server, new ConsoleEventArgs()
                        {
                            NewLine = e.Data
                        });

                        if (!string.IsNullOrEmpty(e.Data))
                        {
                            Match match = Regex.Match(e.Data, downloadProgressRegex, RegexOptions.IgnoreCase);
                            if (match.Success)
                            {
                                UpdateProgress?.Invoke(server, new ServerUpdateProgressEventArgs()
                                {
                                    Progress = float.Parse(match.Groups[2].Value, NumberStyles.Any, ci)
                                });
                            }
                        }
                    };

                    //DataReceivedEventHandler errorEventHandler = (sender, e) =>
                    EventHandler errorEventHandler = (sender, e2) =>
                    {
                        var e = (CustomDataReceivedEventArgs)e2;
                        _logger.LogWarning("SteamCMD emitted {0} - {1}: {2}", server.Id, steamCMDProc.Pid, e.Data);

                        UpdateMessage?.Invoke(server, new ConsoleEventArgs()
                        {
                            NewLine = e.Data,
                            IsError = true
                        });
                    };

                    // Start process
                    var hasErrored          = false;
                    var processExitedCTS    = new CancellationTokenSource();
                    var processExitedCToken = processExitedCTS.Token;
                    try
                    {
                        steamCMDProc = await _steamCMDService.CreateSteamCMD(steamCMDArguments);

                        //steamCMDProc.OutputDataReceived += outputEventHandler;
                        //steamCMDProc.ErrorDataReceived += errorEventHandler;

                        //steamCMDProc.Start();
                        //steamCMDProc.BeginOutputReadLine();
                        //steamCMDProc.BeginErrorReadLine();

                        // Exit event
                        var processExitedTcs = new TaskCompletionSource <uint>();
                        steamCMDProc.ProcessExited += (sender, e) =>
                        {
                            processExitedTcs.TrySetResult((uint)steamCMDProc.ExitCode);
                            processExitedCTS.Cancel();
                            //steamCMDProc.ReaderStream.Close();
                            //steamCMDProc.ReaderStream.Dispose();
                        };

                        server.UpdatePID = steamCMDProc.Pid;

                        db.Update(server);
                        await db.SaveChangesAsync();

                        ServerUpdateStart?.Invoke(server, new EventArgs());                 // Event


                        // Reading console
                        var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
                        var decoder  = encoding.GetDecoder();
                        var sb       = new StringBuilder();

                        var byteBuffer        = new byte[1024];
                        var maxCharsPerBuffer = encoding.GetMaxCharCount(1024);
                        var charBuffer        = new char[maxCharsPerBuffer];

                        int  currentLinePos      = 0;
                        bool bLastCarriageReturn = false;
                        while (!processExitedTcs.Task.IsCompleted)
                        {
                            try
                            {
                                var bytesRead = await steamCMDProc.ReaderStream.ReadAsync(byteBuffer, 0, byteBuffer.Length).WithCancellation(processExitedCToken);

                                if (bytesRead == 0)
                                {
                                    break;
                                }

                                int charLen = decoder.GetChars(byteBuffer, 0, bytesRead, charBuffer, 0);
                                sb !.Append(charBuffer, 0, charLen);

                                MonitorUtils.MoveLinesFromStringBuilderToMessageQueue(ref currentLinePos, ref bLastCarriageReturn, sb,
                                                                                      (line) => outputEventHandler?.Invoke(steamCMDProc, new CustomDataReceivedEventArgs(line)));
                            }
                            catch (OperationCanceledException)
                            {
                                break;
                            }
                        }

                        if (!processExitedTcs.Task.IsCompleted)
                        {
                            await processExitedTcs.Task;
                        }


                        /*
                         * var readStdOut = Task.Run(async delegate
                         * {
                         *      string? line = null;
                         *      //while ((line = await steamCMDProc.StandardOutput.ReadLineAsync()) != null)
                         *      while (steamCMDProc.StandardOutput.Peek() > -1)
                         *      {
                         *              line = steamCMDProc.StandardOutput.ReadLine();
                         *              _logger.LogWarning("Read line! {0}", line);
                         *              outputEventHandler.Invoke(steamCMDProc, new CustomDataReceivedEventArgs(line));
                         *      }
                         * });
                         * var readErrOut = Task.Run(async delegate
                         * {
                         *      string? line = null;
                         *      //while ((line = await steamCMDProc.StandardError.ReadLineAsync()) != null)
                         *      while (steamCMDProc.StandardError.Peek() > -1)
                         *      {
                         *              line = steamCMDProc.StandardError.ReadLine();
                         *              errorEventHandler.Invoke(steamCMDProc, new CustomDataReceivedEventArgs(line));
                         *      }
                         * });
                         *
                         * await Task.WhenAll(readStdOut, readErrOut);
                         */

                        //await steamCMDProc.WaitForExitAsync();
                        //steamCMDProc.WaitForExit();

                        //steamCMDProc.CancelOutputRead();
                        //steamCMDProc.CancelErrorRead();

                        try
                        {
                            if (steamCMDProc.ExitCode != 0)
                            {
                                hasErrored = true;
                                throw new Exception();
                            }
                        }
                        catch (InvalidOperationException err)
                        {
                            // Do nothing, for some f*****g reason it seems it can't get the exit code
                        }
                    }
                    catch (Exception err)
                    {
                        _logger.LogError(err, "There has been an error while updating the server via SteamCMD");
                        return(false);
                    }
                    finally
                    {
                        _logger.LogInformation("Update finished for server {0}!", server.Id);

                        server.UpdatePID = null;
                        db.Update(server);

                        await db.SaveChangesAsync();


                        ServerUpdated?.Invoke(server, new ServerUpdateEventArgs()
                        {
                            Error = hasErrored
                        });

                        if (steamCMDProc != null)
                        {
                            //steamCMDProc.OutputDataReceived -= outputEventHandler;
                            //steamCMDProc.ErrorDataReceived -= errorEventHandler;
                            steamCMDProc.Dispose();
                        }
                        processExitedCTS.Dispose();
                    }
                }

            return(true);
        }