/// <summary> /// Writes an information message to the log including the exception information. /// </summary> /// <param name="ex">Exception to be logged.</param> public static void LogInfo(Exception ex) { ExceptionFormatter exceptionFormatter = new ExceptionFormatter(); string message = exceptionFormatter.FormatException(ex); EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Information, INFO_EVENT_ID); }
public ActionResult GetBotRequest() { try { var userInfo = this.authenticationProvider.Authenticate(this.HttpContext); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } var request = this.userHelper.GetBotRequest(userInfo.GetUserID()); return(Json(request)); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
/// <summary> /// Writes a warning message to the log including the exception information. /// </summary> /// <param name="ex">Exception to be logged.</param> public static void LogWarning(Exception ex) { ExceptionFormatter exceptionFormatter = new ExceptionFormatter(); string message = exceptionFormatter.FormatException(ex); EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Warning, WARN_EVENT_ID); }
/// <summary> /// Writes an information message to the log including the exception information. /// </summary> /// <param name="message">A string containing the message to be logged.</param> /// <param name="ex">Exception to be logged.</param> /// <param name="includeStackTrace">A flag indicating whether or not call stack details should be included.</param> public static void LogInfo(string message, Exception ex, bool includeStackTrace) { ExceptionFormatter exceptionFormatter = new ExceptionFormatter(); message = string.Format(EXECPTION_FORMAT, message, exceptionFormatter.FormatException(ex, includeStackTrace)); EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Information, INFO_EVENT_ID); }
public ActionResult UnlinkBot() { try { var userInfo = this.authenticationProvider.Authenticate(this.HttpContext); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } var deleted = this.userHelper.DeleteBotAccount(userInfo.GetUserID()); if (deleted) { // Restart their bot: var config = this.userHelper.GetConfigurationForUser(userInfo.GetUserID()); if (config != null && config.basicConfiguration.botEnabled) { Startup.chatBotManager.UnregisterConnection(userInfo.GetUserID()); Startup.chatBotManager.RegisterConnection(config); } } return(Json(new { })); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
public ActionResult GetAllUsers() { try { var userInfo = this.authenticationProvider.Authenticate(this.HttpContext); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } if (userInfo.GetUserID().ToLower() != "komaru") { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Not an admin")); } var allUsers = this.userHelper.GetAllUserIDs(); return(Json(new { activeUsers = allUsers.Where(x => x.botEnabled).ToList(), inactiveUsers = allUsers.Where(x => !x.botEnabled).ToList(), })); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
/// <summary> /// Writes an error message to the log including the exception information. /// </summary> /// <param name="message">A string containing the message to be logged.</param> /// <param name="ex">Exception to be logged.</param> public static void LogError(string message, Exception ex) { ExceptionFormatter exceptionFormatter = new ExceptionFormatter(); message = string.Format(EXECPTION_FORMAT, message, exceptionFormatter.FormatException(ex)); EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Error, ERROR_EVENT_ID); }
/// <summary> /// Writes an error message to the log including the exception information. /// </summary> /// <param name="ex">Exception to be logged.</param> /// <param name="includeStackTrace">A flag indicating whether or not call stack details should be included.</param> public static void LogError(Exception ex, bool includeStackTrace) { ExceptionFormatter exceptionFormatter = new ExceptionFormatter(); string message = exceptionFormatter.FormatException(ex, includeStackTrace); EventLog.WriteEntry(EVENT_SOURCE, message, EventLogEntryType.Error, ERROR_EVENT_ID); }
public ActionResult AcceptRequestBot( [FromBody] _tmp2 requestingTwitchUsername ) { try { string token; var userInfo = this.authenticationProvider.Authenticate(this.HttpContext, out token); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } if (requestingTwitchUsername == null) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"Missing Requested Twitch Username")); } if (string.IsNullOrWhiteSpace(requestingTwitchUsername.requestingTwitchUsername)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"Invalid Requesting Twitch Username")); } var botRequest = this.userHelper.GetBotRequest(userInfo.GetUserID()); if (botRequest == null) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, new { message = $"Your Twitch account has not been requested to act as a bot for another user." })); } if (botRequest.requestingUsername != requestingTwitchUsername.requestingTwitchUsername) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, new { message = $"Your Twitch account has been requested by {botRequest.requestingUsername}. Please re-send the bot request while logged in as {requestingTwitchUsername}" })); } this.userHelper.AcceptBotRequest(botRequest, token); // Restart their bot: var config = this.userHelper.GetConfigurationForUser(botRequest.requestingUserID); if (config != null && config.basicConfiguration.botEnabled) { Startup.chatBotManager.UnregisterConnection(botRequest.requestingUserID); Startup.chatBotManager.RegisterConnection(config); } return(Json(new { })); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
private static void Report(Exception e) { var logger = LogManager.GetLogger("UnHandledException"); logger.Fatal(ExceptionFormatter.FormatException(e)); var reportWindow = new ReportWindow(e); reportWindow.Show(); }
private void Cl_OnConnectionError(object sender, OnConnectionErrorArgs e) { try { this.logger.LogError("An Exception Occurred Connecting! Perhaps restarting could help? Error username: {e.BotUsername} | Error message: {e.Error}"); } catch (Exception exc) { this.logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); } }
private void Cl_OnIncorrectLogin(object sender, OnIncorrectLoginArgs e) { try { doNotReconnect = true; this.logger.LogWarning($"Incorrect Login Exception Occurred."); } catch (Exception exc) { this.logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); } }
/// <summary> /// 添加参数 /// </summary> /// <param name="parameter">Exception 类型的参数</param> /// <returns>当前LogInfo实例</returns> public LogInfo AppendParameter(Exception parameter) { if (parameter == null) { Args.Add(NULL_STRING); } else { Args.Add(ExceptionFormatter.FormatException(parameter)); } return(this); }
private void onConnected(object sender, OnConnectedArgs e) { try { this.twitchClient.JoinChannel(this.channelDetails.channelName); reconnectTryCt = 0; this.logger.LogInformation("Connected! Channel: #" + channelDetails.channelName); } catch (Exception exc) { this.logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); } }
public ActionResult Update( [FromBody] HypeCommandsSettings settings ) { try { if (settings == null) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"{nameof(settings)} is null")); } if (string.IsNullOrWhiteSpace(settings.userID)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"{nameof(settings.userID)} is null")); } var userInfo = this.authenticationProvider.Authenticate(this.HttpContext); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } if (settings.userID != userInfo.GetUserID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(settings.userID)} is not yours")); } var validationResult = settings.validate(); if (validationResult != System.ComponentModel.DataAnnotations.ValidationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, new { message = validationResult.ErrorMessage })); } this.userHelper.SaveSettings(settings); Startup.chatBotManager.UpdateConnection(userInfo.GetUserID(), settings.hypeCommands); return(Json(settings)); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
public ActionResult RequestBot( [FromBody] _tmp1 requestedTwitchUsername ) { try { var userInfo = this.authenticationProvider.Authenticate(this.HttpContext); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } if (requestedTwitchUsername == null) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"Missing Requested Twitch Username")); } if (string.IsNullOrWhiteSpace(requestedTwitchUsername.requestedTwitchUsername)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"Invalid Requested Twitch Username")); } if (requestedTwitchUsername.requestedTwitchUsername == userInfo.GetUserID()) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, new { message = $"You can't user your own account as a bot for yourself." })); } this.userHelper.SendBotRequest(new AlternativeUserBotRequest { requestedBotUsername = requestedTwitchUsername.requestedTwitchUsername, requestingUserID = userInfo.GetUserID(), requestingUsername = userInfo.GetUserID(), }); return(Json(new { })); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
public ActionResult GetAll(string auth = null) { try { var userInfo = this.authenticationProvider.Authenticate("Bearer " + auth); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } var botSettings = this.userHelper.EnsureDefaultUserSettings(userInfo.GetUserID()); var ceresSettings = this.userHelper.EnsureDefaultCeresSettings(userInfo.GetUserID()); var gambleSettings = this.userHelper.EnsureDefaultGambleSettings(userInfo.GetUserID()); var hypeSettings = this.userHelper.EnsureDefaultHypeSettings(userInfo.GetUserID()); var botInfo = this.userHelper.GetBotAccount(true, userInfo.GetUserID()); if (botInfo != null) { botSettings.linkedBotAccount = botInfo.username; } var json = JsonConvert.SerializeObject(new { botSettings, ceresSettings, gambleSettings, hypeSettings }); var fileName = "KomaruBotBackup" + DateTime.Now.ToString("yyyy-MM-dd") + ".json"; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json); var response = File(bytes, "application/json", fileName); return(response); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
private static void Report(Exception e, bool waitForClose) { if (e != null) { var logger = LogManager.GetLogger("UnHandledException"); logger.Fatal(ExceptionFormatter.FormatException(e)); var reportWindow = new ReportWindow(e); if (waitForClose) { reportWindow.ShowDialog(); } else { reportWindow.Show(); } } }
/// <summary> /// 写入错误日志 /// </summary> /// <param name="ex">异常</param> /// <param name="parameters">日志参数数组</param> public void Error(Exception ex, params object[] parameters) { StringBuilder sb = new StringBuilder(); foreach (object obj in parameters) { if (obj != null) { sb.Append(obj.ToString()); sb.Append(" "); } else { sb.Append(NULL_STRING); sb.Append(" "); } } logger.Error(sb.ToString() + Environment.NewLine + ExceptionFormatter.FormatException(ex)); }
/// <summary> /// 日志实体类构造函数 /// </summary> /// <param name="format"></param> /// <param name="args"></param> public LogInfo(string format, params object[] args) { this.Format = format; for (int i = 0; i < args.Length; i++) { if (args[i] == null) { Args.Add(NULL_STRING); } else { if (args[i] is Exception) { Args.Add(ExceptionFormatter.FormatException(args[i] as Exception)); } else { Args.Add(args[i].ToString()); } } } }
private void Cl_OnDisconnected(object sender, OnDisconnectedArgs e) { try { reconnectTryCt++; if (reconnectTryCt >= maxRetryCt) { doNotReconnect = true; } if (doNotReconnect) { this.logger.LogWarning("Chat Disconnected. Not attempting to reconnect.", true); } else { new Thread(() => { try { this.logger.LogWarning($"Chat Disconnected. Trying to reconnect (attempt {reconnectTryCt}) in 15 seconds... "); Thread.Sleep(15000); this.logger.LogWarning($"Attempt {reconnectTryCt} Connecting..."); connect(); } catch (Exception exc) { this.logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name} (ReconnectThread Exception)")); } }).Start(); } } catch (Exception exc) { this.logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); } }
/// <summary> /// 写入错误日志 /// </summary> /// <param name="ex">异常</param> public void Error(Exception ex) { logger.Error(ExceptionFormatter.FormatException(ex)); }
private void globalChatMessageReceived(object sender, OnMessageReceivedArgs e) { try { var command = GetCommand(e.ChatMessage.Message); if ((command == null) || (this.ceres != null && command.requiredRoundStarted && !this.ceres.RoundRunning) || (this.ceres != null && command.requiredRoundNotStarted && this.ceres.RoundRunning) ) { return; } var callerAccessLevel = Constants.AccessLevel.Public; if (e.ChatMessage.IsModerator) { callerAccessLevel = Constants.AccessLevel.Moderator; } if (e.ChatMessage.IsBroadcaster) { callerAccessLevel = Constants.AccessLevel.Broadcaster; } if (command.requiredAccessLevel > callerAccessLevel) { return; } if (command.globalTimeout.HasValue) { var key = command.commandText + "_" + command.commandType.ToString(); lock (globalTimeouts) { DateTime allowedAgain; if (globalTimeouts.TryGetValue(key, out allowedAgain)) { if (DateTime.Now < allowedAgain) { // We can't use this command yet because the currenttime is less than the allowed time return; } globalTimeouts.Remove(key); } globalTimeouts.Add(key, DateTime.Now.AddSeconds(command.globalTimeout.Value)); } } if (command.userTimeout.HasValue) { var key = command.commandText + "_" + command.commandType.ToString() + "_" + e.ChatMessage.Username; lock (userTimeouts) { DateTime allowedAgain; if (userTimeouts.TryGetValue(key, out allowedAgain)) { if (DateTime.Now < allowedAgain) { // We can't use this command yet because the currenttime is less than the allowed time return; } userTimeouts.Remove(key); } userTimeouts.Add(key, DateTime.Now.AddSeconds(command.userTimeout.Value)); } } command.onRun(e.ChatMessage, command); } catch (Exception exc) { this.logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); } }
public ActionResult Update( [FromBody] UserBotSettings settings ) { try { if (settings == null) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"{nameof(settings)} is null")); } if (string.IsNullOrWhiteSpace(settings.userID)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"{nameof(settings.userID)} is null")); } if (string.IsNullOrWhiteSpace(settings.currencyPlural)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"{nameof(settings.currencyPlural)} is null")); } if (string.IsNullOrWhiteSpace(settings.currencySingular)) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, $"{nameof(settings.currencySingular)} is null")); } var userInfo = this.authenticationProvider.Authenticate(this.HttpContext); if (userInfo.Result != Constants.AuthenticationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"Could not authenticate")); } if (this.appSettings.TwitchClientID != userInfo.GetClientID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(this.appSettings.TwitchClientID)} does not match")); } if (settings.userID != userInfo.GetUserID()) { return(StatusCode((int)System.Net.HttpStatusCode.Unauthorized, $"{nameof(settings.userID)} is not yours")); } var validationResult = settings.validate(); if (validationResult != System.ComponentModel.DataAnnotations.ValidationResult.Success) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, new { message = validationResult.ErrorMessage })); } var currentSettings = this.userHelper.EnsureDefaultUserSettings(userInfo.GetUserID()); var pointsManager = this.userHelper.GetPointsManager(settings); if (settings.streamElementsAccountID != currentSettings.streamElementsAccountID || settings.streamElementsJWTToken != currentSettings.streamElementsJWTToken) { var setupCorrect = pointsManager.CheckSettingsCorrect(userInfo.GetUserID()); if (!setupCorrect) { return(StatusCode((int)System.Net.HttpStatusCode.BadRequest, new { message = "Could not verify Stream Elements Account settings. Please make sure they're configured correctly." })); } } settings.linkedBotAccount = null; // Don't save this value this.userHelper.SaveSettings(settings); if (settings.basicBotConfiguration.botEnabled) { var config = this.userHelper.GetConfigurationForUser(settings); if (config != null) { var botJustCreated = Startup.chatBotManager.RegisterConnection(config); if (!botJustCreated) { Startup.chatBotManager.UpdateConnection(userInfo.GetUserID(), pointsManager, config.basicConfiguration); } } else { this._logger.LogError($"UserID {settings.userID} got back null as BotConfiguration"); } } else { Startup.chatBotManager.UnregisterConnection(settings.userID); } return(Json(settings)); } catch (Exception exc) { this._logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name}")); return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError)); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; if (env.IsDevelopment()) { loggerFactory.AddFile("Logs/KomaruBot-{Date}.txt", LogLevel.Warning); } else { loggerFactory.AddAWSProvider(this.Configuration.GetAWSLoggingConfigSection(), formatter: (logLevel, message, exception) => $"[{DateTime.UtcNow}] {logLevel}: {message}"); } app.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new List <string> { "index.html" }, }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseMvc(); var settings = app.ApplicationServices.GetService <IOptions <Models.AppSettings> >(); chatBotManager = new ChatBot.ChatBotManager(loggerFactory.CreateLogger("ChatBot"), settings.Value.ChatBotTwitchUsername, settings.Value.ChatBotTwitchOauthToken); var logger = loggerFactory.CreateLogger("Startup"); logger.LogInformation("Application starting up..."); List <ChatBot.ClientConfiguration> configurations = null; try { var userHelper = app.ApplicationServices.GetService <UserHelper>(); configurations = userHelper.GetAllUserClientConfigurations(); logger.LogInformation($"Loaded {configurations.Count} chat bots. Starting them... Chatbot names: {string.Join(", ", configurations.Select(x => x.channelName).ToArray())}"); foreach (var a in configurations) { chatBotManager.RegisterConnection(a); } } catch (Exception exc) { logger.LogError(ExceptionFormatter.FormatException(exc, $"Exception in {this.GetType().Name} - {System.Reflection.MethodBase.GetCurrentMethod().Name} - Starting chatbots")); } keepAlive = new KeepAliveHelper(loggerFactory.CreateLogger("KeepAlive"), settings.Value.ClientUrl + "/api/keepalive"); logger.LogInformation("Application started up."); }
/// <summary> /// 写入错误日志 /// </summary> /// <param name="ex">异常</param> /// <param name="message">其它日志信息</param> public void Error(Exception ex, string message) { logger.Error(message + Environment.NewLine + ExceptionFormatter.FormatException(ex)); }