Beispiel #1
0
        static void Main(string[] args)
        {
            ms_bExtractingData = false;
            ASafeLog oLog = new ConsoleLog(new FileLog("FullCustomerModelGreps"));

            oLog.NotifyStart();

            if (args.Length < 1)
            {
                oLog.Fatal("No path specified.");
            }
            else
            {
                var oData = new SortedDictionary <string, Stat>();
                ProcessDir(oData, args[0], oLog);

                oLog.Info("Step: Count;Min;Average;Median;Pct75;Pct90;Max");

                foreach (var pair in oData)
                {
                    pair.Value.SetAverage();

                    oLog.Info("{0}: {1}", pair.Key, pair.Value);
                }         // for
            }             // if

            oLog.NotifyStop();
        }         // Main
Beispiel #2
0
 /// <summary>
 /// 初始化全局配置文件并返回当前配置文件内容
 /// 初始化成功后写入到私有属性中,第二次读取则不需要重新读取
 /// </summary>
 public void GlobalConfigFileInit()
 {
     try
     {
         //当读取到文件时直接返回
         if (File.Exists(GlobalConfigPath) && LoadGlobalConfig(out _))
         {
             ConsoleLog.Debug("ConfigIO", "读取配置文件");
             return;
         }
         //没读取到文件时创建新的文件
         ConsoleLog.Error("ConfigIO", "未找到配置文件");
         ConsoleLog.Warning("ConfigIO", "创建新的配置文件");
         string initConfigText = Encoding.UTF8.GetString(InitRes.InitGlobalConfig);
         using (TextWriter writer = File.CreateText(GlobalConfigPath))
         {
             writer.Write(initConfigText);
             writer.Close();
         }
         //读取生成的配置文件
         if (!LoadGlobalConfig(out _))
         {
             throw new IOException("无法读取生成的配置文件");
         }
     }
     catch (Exception e)
     {
         ConsoleLog.Fatal("ConfigIO ERROR", ConsoleLog.ErrorLogBuilder(e));
         Thread.Sleep(5000);
         Environment.Exit(-1);
     }
 }
        Task LogClientAsync(LogMessage msg)
        {
            switch (msg.Severity)
            {
            case LogSeverity.Critical:
            case LogSeverity.Error:
                ConsoleLog.Fatal("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                if (msg.Severity == LogSeverity.Error)
                {
                    ConsoleLog.Error("Discord", $"[{msg.Source}] " + ConsoleLog.ErrorLogBuilder(msg.Exception));
                }
                break;

            case LogSeverity.Warning:
                ConsoleLog.Warning("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                break;

            case LogSeverity.Info:
                ConsoleLog.Info("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                break;

            case LogSeverity.Verbose:
            case LogSeverity.Debug:
                ConsoleLog.Debug("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                break;

            default:
                break;
            }
            ;
            return(Task.CompletedTask);
        }
Beispiel #4
0
 /// <summary>
 /// 初始化配置文件并返回当前配置文件内容
 /// </summary>
 private void ConfigFileInit()
 {
     try
     {
         //当读取到文件时直接返回
         if (File.Exists(Path) && LoadConfig())
         {
             ConsoleLog.Debug("ConfigIO", "读取配置文件");
             return;
         }
         //没读取到文件时创建新的文件
         ConsoleLog.Warning("ConfigIO", "未找到配置文件");
         ConsoleLog.Info("ConfigIO", "创建新的配置文件");
         Serializer serializer  = new Serializer(new SerializerSettings {
         });
         ConfigClass config     = getInitConfigClass();
         string      configText = serializer.Serialize(config);
         using TextWriter writer = File.CreateText(Path);
         writer.Write(configText);
         LoadedConfig = config;
     }
     catch (Exception e)
     {
         ConsoleLog.Fatal("ConfigIO ERROR", ConsoleLog.ErrorLogBuilder(e));
         Thread.Sleep(5000);
         Environment.Exit(-1);
     }
 }
Beispiel #5
0
 /// <summary>
 /// 服务器链接关闭事件
 /// </summary>
 /// <param name="role">通道标识</param>
 /// <param name="selfId">事件源</param>
 /// <param name="socket">连接信息</param>
 internal void CloseConnection(string role, string selfId, IWebSocketConnection socket)
 {
     if (!RemoveConnection(socket.ConnectionInfo.Id))
     {
         ConsoleLog.Fatal("Sora", "客户端连接被关闭失败");
         ConsoleLog.Warning("Sora", "将会立即重启");
         new Process()
         {
             StartInfo =
             {
                 FileName        = AppDomain.CurrentDomain.BaseDirectory + "Qiushui.Lian.Bot.exe",
                 UseShellExecute = false
             }
         }.Start();
         Environment.Exit(-1);
     }
     if (OnCloseConnectionAsync == null)
     {
         return;
     }
     long.TryParse(selfId, out long uid);
     Task.Run(async() =>
     {
         await OnCloseConnectionAsync(socket.ConnectionInfo,
                                      new ConnectionEventArgs(role, uid));
     });
 }
Beispiel #6
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="eventArgs">CQAppEnableEventArgs</param>
        public static void Init(ConnectEventArgs eventArgs)
        {
            string DBPath = SugarUtils.GetDBPath(eventArgs.LoginUid.ToString());

            ConsoleLog.Debug("IO", $"获取数据路径{DBPath}");
            if (!File.Exists(DBPath))//查找数据文件
            {
                //数据库文件不存在,新建数据库
                ConsoleLog.Warning("数据库初始化", "未找到数据库文件,创建新的数据库");
                Directory.CreateDirectory(Path.GetPathRoot(DBPath) ?? String.Empty);
                File.Create(DBPath).Close();
            }
            SqlSugarClient dbClient = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString      = $"DATA SOURCE={DBPath}",
                DbType                = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType           = InitKeyType.Attribute
            });

            try
            {
                if (!SugarUtils.TableExists <SuiseiData>(dbClient)) //彗酱数据库初始化
                {
                    ConsoleLog.Warning("数据库初始化", "未找到慧酱数据表 - 创建一个新表");
                    SugarUtils.CreateTable <SuiseiData>(dbClient);
                }
                if (!SugarUtils.TableExists <MemberInfo>(dbClient)) //成员状态表的初始化
                {
                    ConsoleLog.Warning("数据库初始化", "未找到成员状态表 - 创建一个新表");
                    SugarUtils.CreateTable <MemberInfo>(dbClient);
                }
                if (!SugarUtils.TableExists <BiliSubscription>(dbClient)) //动态记录表的初始化
                {
                    ConsoleLog.Warning("数据库初始化", "未找到动态记录表 - 创建一个新表");
                    SugarUtils.CreateTable <BiliSubscription>(dbClient);
                }
                if (!SugarUtils.TableExists <GuildBattleBoss>(dbClient)) //会战数据表的初始化
                {
                    ConsoleLog.Warning("数据库初始化", "未找到会战数据表 - 创建一个新表");
                    SugarUtils.CreateTable <GuildBattleBoss>(dbClient);
                    //写入初始化数据
                    dbClient.Insertable(GuildBattleBoss.GetInitBossInfos()).ExecuteCommand();
                }
                if (!SugarUtils.TableExists <GuildInfo>(dbClient)) //会战状态表的初始化
                {
                    ConsoleLog.Warning("数据库初始化", "未找到会战状态表 - 创建一个新表");
                    SugarUtils.CreateTable <GuildInfo>(dbClient);
                }
            }
            catch (Exception exception)
            {
                ConsoleLog.Fatal("数据库初始化错误", ConsoleLog.ErrorLogBuilder(exception));
                Thread.Sleep(5000);
                throw;
            }
        }
Beispiel #7
0
        static void Launch()
        {
            var cfg = Config = Config.LoadConfig();

#if DEBUG
            ConsoleLog.SetLogLevel(LogLevel.Debug);
            ConsoleLog.Debug("Main", "当前正在使用Debug模式");
#else
            if (cfg.IsDebug)
            {
                ConsoleLog.SetLogLevel(LogLevel.Debug);
                ConsoleLog.Debug("Main", "当前正在使用Debug模式");
            }
            else
            {
                ConsoleLog.SetLogLevel(LogLevel.Info);
            }
#endif
            ConsoleLog.Debug("Main", "Config:\r\n" + JsonConvert.SerializeObject(cfg, Formatting.Indented));

            ConsoleLog.Info("Main", "初始化数据库中……");
            Database.Init(cfg.DatabasePath);
            ConsoleLog.Info("Main", "数据库已装载");

            ConsoleLog.Info("Main", "订阅系统启动中……");
            SubscribeManager.Init();
            ConsoleLog.Info("Main", "订阅系统已装载");

            if (!string.IsNullOrWhiteSpace(Config.Roll_Api_Id) && !string.IsNullOrWhiteSpace(Config.Roll_Api_Secret))
            {
                Library.Roll.RollApi.Init(Config.Roll_Api_Id, Config.Roll_Api_Secret);
                ConsoleLog.Info("Main", "Roll Api 已初始化");
            }

            if (cfg.Discord)
            {
                Working = true;
                ConsoleLog.Info("Main", "已启用Discord功能");
                new Thread(() =>
                {
                    try
                    {
                        DiscordServer = new(cfg.DiscordToken);
                        DiscordServer.Start();
                    }
                    catch (Exception ex)
                    {
                        ConsoleLog.Fatal("Main", "Discord功能启动失败");
                        ConsoleLog.Error("Main", ConsoleLog.ErrorLogBuilder(ex));
                        Working = false;
                    }
                })
                {
                    IsBackground = true
                }.Start();
Beispiel #8
0
 /// <summary>
 /// 创建一个反向WS服务端
 /// </summary>
 /// <param name="config">服务器配置</param>
 /// <param name="crashAction">发生未处理异常时的回调</param>
 public SoraWSServer(ServerConfig config, Action <Exception> crashAction = null)
 {
     //检查端口占用
     if (IsPortInUse(config.Port))
     {
         ConsoleLog.Fatal("Sora", $"端口{config.Port}已被占用,请更换其他端口");
         ConsoleLog.Warning("Sora", "将在5s后自动退出");
         Thread.Sleep(5000);
         Environment.Exit(0);
     }
     serverReady = false;
     ConsoleLog.Info("Sora", $"Sora WebSocket服务器初始化...");
     ConsoleLog.Debug("System", Environment.OSVersion);
     //初始化连接管理器
     ConnManager = new ConnectionManager(config);
     //检查参数
     if (config == null)
     {
         throw new ArgumentNullException(nameof(config));
     }
     if (config.Port == 0 || config.Port > 65535)
     {
         throw new ArgumentOutOfRangeException(nameof(config.Port));
     }
     this.Config = config;
     //API超时
     ApiInterface.TimeOut = config.ApiTimeOut;
     //实例化事件接口
     this.Event = new EventInterface();
     //禁用原log
     FleckLog.Level = (LogLevel)4;
     this.Server    = new WebSocketServer($"ws://{config.Location}:{config.Port}")
     {
         //出错后进行重启
         RestartAfterListenError = true
     };
     //全局异常事件
     AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
     {
         if (crashAction == null)
         {
             FriendlyException(args);
         }
         else
         {
             crashAction(args.ExceptionObject as Exception);
         }
     };
     serverReady = true;
 }
Beispiel #9
0
        static async Task Main(string[] args)
        {
            ConsoleLog.SetLogLevel(LogLevel.Debug);
            ConsoleLog.Debug("dotnet version", Environment.Version);

            SoraWSServer server = new SoraWSServer(new ServerConfig {
                Port = 9200
            });

            //服务器连接事件
            server.ConnManager.OnOpenConnectionAsync += (connectionInfo, eventArgs) =>
            {
                ConsoleLog.Debug("Sora_Test",
                                 $"connectionId = {connectionInfo.Id} type = {eventArgs.Role}");
                return(ValueTask.CompletedTask);
            };
            //服务器连接关闭事件
            server.ConnManager.OnCloseConnectionAsync += (connectionInfo, eventArgs) =>
            {
                ConsoleLog.Debug("Sora_Test",
                                 $"connectionId = {connectionInfo.Id} type = {eventArgs.Role}");
                return(ValueTask.CompletedTask);
            };
            //服务器心跳包超时事件
            server.ConnManager.OnHeartBeatTimeOut += (connectionInfo, eventArgs) =>
            {
                ConsoleLog.Debug("Sora_Test",
                                 $"Get heart beat time out from[{connectionInfo.Id}] uid[{eventArgs.SelfId}]");
                return(ValueTask.CompletedTask);
            };
            //群聊消息事件
            server.Event.OnGroupMessage += async(sender, eventArgs) =>
            {
                await eventArgs.SourceGroup.SendGroupMessage("好耶");
            };
            //私聊消息事件
            server.Event.OnOfflineFileEvent += async(sender, eventArgs) =>
            {
                await eventArgs.Sender.SendPrivateMessage("好耶");
            };
            try
            {
                await server.StartServer();
            }
            catch (Exception e) //侦测所有未处理的错误
            {
                ConsoleLog.Fatal("unknown error", ConsoleLog.ErrorLogBuilder(e));
            }
        }
Beispiel #10
0
 /// <summary>
 /// 运行并检查错误
 /// </summary>
 /// <typeparam name="T">out type</typeparam>
 /// <param name="this">run method</param>
 /// <param name="block">error info out method</param>
 /// <returns>T</returns>
 public static async ValueTask <T> RunCatch <T>(this ValueTask <T> @this, Func <Exception, T> block = null)
 {
     try
     {
         return(await @this);
     }
     catch (Exception ex)
     {
         if (block != null)
         {
             block(ex);
         }
         else
         {
             ConsoleLog.Fatal("Sora", ConsoleLog.ErrorLogBuilder(ex));
         }
         return(default);
Beispiel #11
0
 /// <summary>
 /// 服务器链接关闭事件
 /// </summary>
 /// <param name="role">通道标识</param>
 /// <param name="selfId">事件源</param>
 /// <param name="socket">连接信息</param>
 internal void CloseConnection(string role, string selfId, IWebSocketConnection socket)
 {
     if (!RemoveConnection(socket.ConnectionInfo.Id))
     {
         ConsoleLog.Fatal("Sora", "客户端连接被关闭失败");
         ConsoleLog.Warning("Sora", "将在5s后自动退出");
         Thread.Sleep(5000);
         Environment.Exit(-1);
     }
     if (OnCloseConnectionAsync == null)
     {
         return;
     }
     long.TryParse(selfId, out long uid);
     Task.Run(async() =>
     {
         await OnCloseConnectionAsync(socket.ConnectionInfo,
                                      new ConnectionEventArgs(role, uid));
     });
 }