public async Task <string> StartNewRound() { m_Logger.Info("Start a new round..."); m_RoundStartTime = DateTime.Now; m_RoundIndex++; m_PlayerCards.Clear(); m_BankerCards.Clear(); PlayerPoints = -1; BankerPoints = -1; var newGameId = GetGameId(); m_Logger.Info("New round ID: " + newGameId); m_Logger.Info("Saving new game record to database..."); var saveReq = new { server = m_Node.GetName(), table = TableCode, shoe = m_ShoeCode, round = m_RoundIndex, state = (int)m_GameState, starttime = m_RoundStartTime.ToString("yyyy-MM-dd HH:mm:ss"), updatetime = m_RoundStartTime.ToString("yyyy-MM-dd HH:mm:ss"), player = String.Join(",", m_PlayerCards.ToArray()), banker = String.Join(",", m_BankerCards.ToArray()), result = 0 }; string replystr = await RemoteCaller.RandomCall(m_Node.GetRemoteServices(), "game-data", "save-record", m_Node.GetJsonHelper().ToJsonString(saveReq)); if (replystr == "ok") { m_Logger.Info("Update database successfully"); } else { m_Logger.Error("Failed to save game data to database"); } m_GameReadyCountdown = -1; m_BettingTimeCountdown = BET_TIME_COUNTDOWN; //m_GameState = GAME_STATUS.BettingTime; UpdateRoundState(GAME_STATUS.BettingTime); m_Logger.Info("Start betting time..."); return(""); }
private void Deliver() { List <dynamic> list = new List <dynamic>(); var dbhelper = m_Node.GetDataHelper(); using (var cnn = dbhelper.OpenDatabase(m_MainCache)) { using (var cmd = cnn.CreateCommand()) { cmd.CommandText = "select * from tbl_round_state where backup_number = 0 "; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var item = new { server = reader["server_code"].ToString(), table = reader["table_code"].ToString(), label = reader["table_name"].ToString(), game = reader["game_type"].ToString(), shoe = reader["shoe_code"].ToString(), round = reader["round_number"].ToString(), state = reader["round_state"].ToString(), status = reader["round_state_text"].ToString(), players = reader["player_count"].ToString(), bet_countdown = reader["bet_time_countdown"].ToString(), game_countdown = reader["gaming_countdown"].ToString(), next_countdown = reader["next_game_countdown"].ToString(), starttime = Convert.ToDateTime(reader["round_start_time"]).ToString("yyyy-MM-dd HH:mm:ss"), updatetime = Convert.ToDateTime(reader["round_update_time"]).ToString("yyyy-MM-dd HH:mm:ss"), //history = reader["game_history"].ToString(), //remark = reader["game_remark"].ToString(), output = reader["game_output"].ToString(), result = reader["game_result"].ToString() }; list.Add(item); } } } } try { var clientMsg = new { msg = "table_info", tables = list }; var server = m_Node.GetPublicServer(); if (server != null && server.IsWorking()) { server.Broadcast(m_Node.GetJsonHelper().ToJsonString(clientMsg)); } } catch (Exception ex) { Console.WriteLine("FES Broadcast Error - " + ex.ToString()); } }
public void OnConnect(IWebSession session) { //Console.WriteLine(m_LocalNode.GetName() + " - OnConnect: " + session.GetRemoteAddress()); //System.Diagnostics.Debugger.Break(); //m_LocalNode.GetLogger().Info("OnClientConnect: " + session.GetRequestPath()); var clientMsg = new { msg = "client_info", client_id = session.GetRemoteAddress(), front_end = m_LocalNode.GetName(), action = "connect" }; var server = m_LocalNode.GetPublicServer(); if (server != null && server.IsWorking()) { session.Send(m_LocalNode.GetJsonHelper().ToJsonString(clientMsg)); } }
public string GetMerchantInfo(string merchantKey) { var info = ""; var merchants = m_Merchants; if (merchants.ContainsKey(merchantKey)) { var item = merchants[merchantKey]; if (item.active > 0) { info = m_Node.GetJsonHelper().ToJsonString(item); } } return(info); }
public void OnConnect(IWebSession session) { //Console.WriteLine(m_LocalNode.GetName() + " - OnConnect: " + session.GetRemoteAddress()); //m_LocalNode.GetLogger().Info("OnClientConnect: " + session.GetRequestPath()); if (m_Clients == null) { session.CloseConnection(); return; } var count = 0; var playerId = ""; var merchantCode = ""; var currencyCode = ""; var sessionId = ""; var parts = session.GetRequestPath().Split('/'); foreach (var part in parts) { if (part.Length <= 0) { continue; } count++; if (count == 1) { merchantCode = part; } if (count == 2) { currencyCode = part; } if (count == 3) { playerId = part; } if (count == 4) { sessionId = part; } if (count > 4) { break; } } var okay = false; var clientToken = ""; if (!String.IsNullOrEmpty(merchantCode) && !String.IsNullOrEmpty(currencyCode) && !String.IsNullOrEmpty(playerId) && !String.IsNullOrEmpty(sessionId)) { var dbhelper = m_LocalNode.GetDataHelper(); using (var cnn = dbhelper.OpenDatabase(m_MainCache)) { using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@session_id", sessionId); dbhelper.AddParam(cmd, "@merchant_code", merchantCode); dbhelper.AddParam(cmd, "@currency_code", currencyCode); dbhelper.AddParam(cmd, "@player_id", playerId); cmd.CommandText = " select * from tbl_player_session " + " where merchant_code = @merchant_code " + " and currency_code = @currency_code " + " and player_id = @player_id " + " and session_id = @session_id " ; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { okay = true; } } } if (okay) { clientToken = Guid.NewGuid().ToString(); using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@client_token", clientToken); dbhelper.AddParam(cmd, "@session_id", sessionId); dbhelper.AddParam(cmd, "@merchant_code", merchantCode); dbhelper.AddParam(cmd, "@currency_code", currencyCode); dbhelper.AddParam(cmd, "@player_id", playerId); cmd.CommandText = " update tbl_player_session " + " set client_token = @client_token, update_time = NOW() " + " where merchant_code = @merchant_code " + " and currency_code = @currency_code " + " and player_id = @player_id " + " and session_id = @session_id " ; okay = cmd.ExecuteNonQuery() > 0; } } } } //if (okay) m_LocalNode.GetLogger().Info("Client session is ok: " + sessionId); //else m_LocalNode.GetLogger().Info("Invalid session: " + sessionId); if (okay && m_Clients != null) { m_Clients.AddClient(session.GetRemoteAddress(), merchantCode, currencyCode, playerId, session); var clientMsg = new { msg = "client_info", client_id = session.GetRemoteAddress(), front_end = m_LocalNode.GetName(), client_token = clientToken, action = "connect" }; var server = m_LocalNode.GetPublicServer(); if (server != null && server.IsWorking()) { session.Send(m_LocalNode.GetJsonHelper().ToJsonString(clientMsg)); } } else { session.CloseConnection(); } }
public async Task <string> PlayerLogin(string jsonRequest) { if (m_LocalNode == null) { return(m_LocalNode.GetJsonHelper().ToJsonString(new { error_code = -1, error_message = "Service is not available" })); } m_LocalNode.GetLogger().Info("call merchant api: player-login"); dynamic req = m_LocalNode.GetJsonHelper().ToJsonObject(jsonRequest); string merchantUrl = req.merchant_url.ToString(); m_LocalNode.GetLogger().Info("Player login - [" + req.merchant_code.ToString() + "] " + req.player_id.ToString()); m_LocalNode.GetLogger().Info("Merchant URL - " + merchantUrl); dynamic ret = null; var apiReq = new { req.merchant_code, req.currency_code, req.player_id, req.login_token }; try { var rawret = await RemoteCaller.Request <Tuple <int, string> >(merchantUrl + "/player/validate-login", apiReq, null, 10 * 1000); m_LocalNode.GetLogger().Info("3-Way Login Reply Code: " + rawret.Item1); ret = m_LocalNode.GetJsonHelper().ToJsonObject(rawret.Item2); } catch (Exception ex) { ret = null; m_LocalNode.GetLogger().Error("Three-Way Login Error - Failed to call merchant API: " + ex.Message); } if (ret == null) { return(null); } if (ret.error_code != 0) { m_LocalNode.GetLogger().Error("Three-Way Login Error: " + (ret == null ? "Failed to call merchant API" : ret.error_message)); return(m_LocalNode.GetJsonHelper().ToJsonString(new { error_code = -1, error_message = "Three-Way Login Error" })); } return(m_LocalNode.GetJsonHelper().ToJsonString(ret)); }
private async void Deliver() { Dictionary <string, List <dynamic> > betResults = new Dictionary <string, List <dynamic> >(); var dbhelper = m_Node.GetDataHelper(); using (var cnn = dbhelper.OpenDatabase(m_MainCache)) { using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@front_end", m_ServerName); cmd.CommandText = " update tbl_bet_record " + " set bet_state = 2 " // that means we are going to send them + " where front_end = @front_end and bet_state = 1 "; cmd.ExecuteNonQuery(); } using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@front_end", m_ServerName); // select records which are ready to be sent cmd.CommandText = " select * from tbl_bet_record " + " where front_end = @front_end and bet_state = 2 "; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var item = new { client = reader["client_id"].ToString(), server = reader["server_code"].ToString(), table = reader["table_code"].ToString(), shoe = reader["shoe_code"].ToString(), round = Convert.ToInt32(reader["round_number"].ToString()), pool = Convert.ToInt32(reader["bet_pool"].ToString()), bet_type = Convert.ToInt32(reader["bet_type"].ToString()), bet_input = reader["game_input"].ToString(), bet_id = reader["bet_uuid"].ToString(), bet = Convert.ToDecimal(reader["bet_amount"].ToString()), payout = Convert.ToDecimal(reader["pay_amount"].ToString()), result = reader["game_result"].ToString() }; if (betResults.ContainsKey(item.client)) { var list = betResults[item.client]; list.Add(item); } else { var list = new List <dynamic>(); list.Add(item); betResults.Add(item.client, list); } } } } using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@front_end", m_ServerName); // remove them cmd.CommandText = " delete from tbl_bet_record " + " where front_end = @front_end and bet_state = 2 "; cmd.ExecuteNonQuery(); } } foreach (var item in betResults) { try { var list = item.Value; var clientMsg = new { msg = "bet_result", results = list }; ClientInfo client = null; if (m_Clients.TryGetValue(item.Key, out client)) { await client.Session.Send(m_Node.GetJsonHelper().ToJsonString(clientMsg)); } } catch (Exception ex) { Console.WriteLine("FES Send-Bet-Result Error - " + ex.ToString()); } } if (betResults.Count > 0) { m_Logger.Info("Sent bet results to clients - " + betResults.Count); } }
public async Task <dynamic> AcceptBet(dynamic betreq) { string replyMsgType = "bet_reply"; int replyErrorCode = -1; string replyErroMsg = "input invalid"; if (betreq.bet_pool < 1) { return(new { msg = replyMsgType, error_code = replyErrorCode, error_msg = replyErroMsg }); } string betGuid = ""; decimal playerBalance = -1; var dbhelper = m_Node.GetDataHelper(); using (var cnn = dbhelper.OpenDatabase(m_MainCache)) { using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@server_code", betreq.server_code); dbhelper.AddParam(cmd, "@table_code", betreq.table_code); dbhelper.AddParam(cmd, "@shoe_code", betreq.shoe_code); dbhelper.AddParam(cmd, "@round_number", betreq.round_number); cmd.CommandText = " select * from tbl_round_state " + " where round_state = 4 and bet_time_countdown > 0 " + " and server_code = @server_code and table_code = @table_code " + " and shoe_code = @shoe_code and round_number = @round_number "; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { replyErrorCode = 2; replyErroMsg = "timing is fine"; } else { replyErrorCode = -2; replyErroMsg = "out of betting time"; } } } if (replyErrorCode >= 0) { m_Logger.Info("Saving bet record to database..."); string betTime = ""; string retStr = await RemoteCaller.RandomCall(m_Node.GetRemoteServices(), "bet-data", "save-record", m_Node.GetJsonHelper().ToJsonString(betreq)); if (retStr.Contains("{") && retStr.Contains("-")) { dynamic ret = m_Node.GetJsonHelper().ToJsonObject(retStr); betGuid = ret.bet_uuid; betTime = ret.bet_time; m_Logger.Info("Update database successfully"); } else { m_Logger.Error("Failed to save bet data in database"); } if (betGuid.Length > 0 && betTime.Length > 0) { // call single wallet m_Logger.Info("Call single wallet..."); var swReq = new { bet_uuid = betGuid, table_code = betreq.table_code, shoe_code = betreq.shoe_code, round_number = betreq.round_number, bet_pool = betreq.bet_pool, merchant_code = betreq.merchant_code, player_id = betreq.player_id, bet_amount = betreq.bet_amount, bet_time = betTime }; string swReplyStr = await RemoteCaller.RandomCall(m_Node.GetRemoteServices(), "single-wallet", "debit-for-placing-bet", m_Node.GetJsonHelper().ToJsonString(swReq)); if (String.IsNullOrEmpty(swReplyStr)) { replyErrorCode = -5; replyErroMsg = "failed to call single-wallet service"; } else { dynamic ret = m_Node.GetJsonHelper().ToJsonObject(swReplyStr); if (ret.error_code == 0) { playerBalance = ret.player_balance; } else { replyErrorCode = -5; replyErroMsg = "failed to debit from merchant"; } } } else { replyErrorCode = -4; replyErroMsg = "failed to add it to db"; } if (replyErrorCode >= 0 && playerBalance >= 0) { using (var cmd = cnn.CreateCommand()) { dbhelper.AddParam(cmd, "@bet_uuid", betGuid); dbhelper.AddParam(cmd, "@merchant_code", betreq.merchant_code); dbhelper.AddParam(cmd, "@player_id", betreq.player_id); dbhelper.AddParam(cmd, "@server_code", betreq.server_code); dbhelper.AddParam(cmd, "@table_code", betreq.table_code); dbhelper.AddParam(cmd, "@shoe_code", betreq.shoe_code); dbhelper.AddParam(cmd, "@round_number", betreq.round_number); dbhelper.AddParam(cmd, "@client_id", betreq.client_id); dbhelper.AddParam(cmd, "@front_end", betreq.front_end); dbhelper.AddParam(cmd, "@bet_pool", betreq.bet_pool); dbhelper.AddParam(cmd, "@bet_amount", betreq.bet_amount); cmd.CommandText = " insert into tbl_bet_record " + " ( bet_uuid, merchant_code, player_id, server_code, table_code, shoe_code, round_number, client_id, front_end, bet_pool, bet_amount, bet_time ) values " + " ( @bet_uuid, @merchant_code, @player_id, @server_code , @table_code , @shoe_code , @round_number , @client_id , @front_end , @bet_pool, @bet_amount , CURRENT_TIMESTAMP ) " ; int rows = cmd.ExecuteNonQuery(); if (rows > 0) { replyErrorCode = 3; replyErroMsg = "added to cache"; } else { replyErrorCode = -3; replyErroMsg = "failed to add it to cache"; } } } } if (replyErrorCode >= 0) { return(new { msg = replyMsgType, player_balance = playerBalance, error_code = 0, error_msg = "ok" }); } else { return new { msg = replyMsgType, player_balance = playerBalance, error_code = replyErrorCode, error_msg = replyErroMsg } }; } } }
public async Task UpdateBetsInDatabase(RequestContext ctx) { string reqstr = ctx.Data.ToString(); if (reqstr.Trim().Length <= 0 || !reqstr.Contains('[')) { await ctx.Session.Send("Invalid request"); return; } dynamic req = ctx.JsonHelper.ToJsonObject(reqstr); List <dynamic> passIds = new List <dynamic>(); List <Task> dbTasks = new List <Task>(); foreach (var item in req) { string uuid = item.bet_uuid.ToString(); dbTasks.Add(Task.Run(async() => { string dbReply = await RemoteCaller.RandomCall(m_Node.GetRemoteServices(), "bet-data", "update-result", m_Node.GetJsonHelper().ToJsonString(item)); //if (dbErr != "ok") errIds.Add(uuid); if (dbReply.Contains('-') && dbReply.Contains('=')) { var itemParts = dbReply.Split('='); passIds.Add(new { bet_uuid = itemParts[0], settle_time = itemParts[1] }); } })); } Task.WaitAll(dbTasks.ToArray()); await ctx.Session.Send(ctx.JsonHelper.ToJsonString(passIds)); }
private async Task TryToCancelDebits() { //System.Diagnostics.Debugger.Break(); //m_Logger.Info("TryToCancelDebits - START -"); var totalCount = 0; Dictionary <string, List <dynamic> > debitItems = new Dictionary <string, List <dynamic> >(); Dictionary <string, dynamic> merchants = new Dictionary <string, dynamic>(); var dbhelper = m_Node.GetDataHelper(); using (var cnn = dbhelper.OpenDatabase(m_CommonMerchantDb)) { using (var cmd = cnn.CreateCommand()) { // select records which need to cancel cmd.CommandText = " select debit_uuid, bet_uuid, player_id, client_id, session_id, " + " merchant_code, currency_code, debit_amount from tbl_trans_debit " + " where is_cancelled = 0 and network_error <> 0 "; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { string debitUuid = reader["debit_uuid"].ToString(); string betUuid = reader["bet_uuid"].ToString(); string playerId = reader["player_id"].ToString(); string clientId = reader["client_id"].ToString(); string sessionId = reader["session_id"].ToString(); string merchantCode = reader["merchant_code"].ToString(); string currencyCode = reader["currency_code"].ToString(); decimal debitAmount = Convert.ToDecimal(reader["debit_amount"].ToString()); var reqIp = clientId; if (reqIp.Contains(":")) { reqIp = reqIp.Split(':')[0]; } var item = new { debit_uuid = debitUuid, trans_uuid = debitUuid + "-cancel", bet_uuid = betUuid, merchant_code = merchantCode, currency_code = currencyCode, player_id = playerId, player_ip = reqIp, session_id = sessionId, amount = debitAmount }; string merchantKey = item.merchant_code + item.currency_code; if (debitItems.ContainsKey(merchantKey)) { var list = debitItems[merchantKey]; list.Add(item); } else { var list = new List <dynamic>(); list.Add(item); debitItems.Add(merchantKey, list); } } } } foreach (var item in debitItems) { if (!merchants.ContainsKey(item.Key)) { string merchantInfo = await RemoteCaller.RandomCall(m_Node.GetRemoteServices(), "merchant-data", "get-merchant-info", item.Key); if (String.IsNullOrEmpty(merchantInfo) || !merchantInfo.Contains('{') || !merchantInfo.Contains(':')) { continue; } dynamic merchant = m_Node.GetJsonHelper().ToJsonObject(merchantInfo); if (merchant != null) { merchants.Add(item.Key, merchant); } } if (!merchants.ContainsKey(item.Key)) { continue; } string apiUrl = merchants[item.Key].url.ToString(); string apiSvc = merchants[item.Key].service.ToString(); var list = item.Value; foreach (var debit in list) { var apiReq = new { merchant_url = apiUrl, debit.trans_uuid, debit.debit_uuid, debit.bet_uuid, debit.merchant_code, debit.currency_code, debit.player_id, debit.player_ip, debit.session_id, debit.amount }; dynamic ret = null; try { string retJson = await CallMerchantApi(apiSvc, "cancel-debit", m_Node.GetJsonHelper().ToJsonString(apiReq)); ret = string.IsNullOrEmpty(retJson) ? null : m_Node.GetJsonHelper().ToJsonObject(retJson); } catch (Exception ex) { ret = null; m_Node.GetLogger().Error("Failed to call cancel debit: " + ex.Message); } try { if (ret != null) { int respCode = ret.error_code; var sql = " update tbl_trans_debit " + " set network_error = 0 , response_error = " + respCode; if (respCode == 0) { sql += " , is_cancelled = 1 "; } sql += " , update_time = NOW() "; sql += " where debit_uuid = @debit_uuid "; var okay = false; var trans = cnn.BeginTransaction(); using (var cmd = cnn.CreateCommand()) { cmd.Transaction = trans; dbhelper.AddParam(cmd, "@debit_uuid", debit.debit_uuid); cmd.CommandText = sql; okay = cmd.ExecuteNonQuery() > 0; } if (okay) { sql = " update tbl_bet_record set cancel_state = 1 "; sql += " , update_time = CURRENT_TIMESTAMP "; if (respCode == 0) { sql += " , cancel_time = CURRENT_TIMESTAMP "; } sql += " where bet_uuid = @bet_uuid "; using (var cmd = cnn.CreateCommand()) { cmd.Transaction = trans; dbhelper.AddParam(cmd, "@bet_uuid", debit.bet_uuid); cmd.CommandText = sql; okay = okay && cmd.ExecuteNonQuery() > 0; } } if (okay) { trans.Commit(); } else { trans.Rollback(); } } totalCount++; } catch (Exception ex) { ret = null; m_Node.GetLogger().Error("Failed to call cancel debit: " + ex.Message); } } // end of debits of same merchant } // end of all debits } // end of using db cnn if (totalCount > 0) { m_Logger.Info("TryToCancelDebits - DONE (" + totalCount + ")"); } }
public async Task <string> Load(IServerNode node) { //System.Diagnostics.Debugger.Break(); node.GetLogger().Info(this.GetType().Name + " is loading settings from config..."); TableGroupSetting tableSettings = null; try { ConfigurationManager.RefreshSection("appSettings"); await Task.Delay(100); var keys = ConfigurationManager.AppSettings.Keys; foreach (var key in keys) { if (key.ToString() == "GameTableSetting") { string settings = ConfigurationManager.AppSettings["GameTableSetting"].ToString(); tableSettings = node.GetJsonHelper().ToJsonObject <TableGroupSetting>(settings); continue; } } } catch (Exception ex) { node.GetLogger().Error("Failed to load settings from config for GameServerService: "); node.GetLogger().Error(ex.ToString()); } //if (m_Game != null) await m_Game.Open(); if (tableSettings != null) { lock (m_GameTables) { foreach (var setting in tableSettings.Tables) { if (m_GameTables.ContainsKey(setting.TableCode)) { continue; } TurnBasedGameTable gameTable = null; if (tableSettings.GameType == GameLogicBigTwo.GAME_TYPE) { gameTable = new TurnBasedGameTable(node, new GameLogicBigTwo()); } if (gameTable != null) { gameTable.TableCode = setting.TableCode; gameTable.TableType = tableSettings.TableType; gameTable.TableName = setting.TableName; gameTable.TestMerchant = tableSettings.TestMerchant; gameTable.TimeToBet = tableSettings.BettingTime; m_GameTables.Add(gameTable.TableCode, gameTable); } } } } else { node.GetLogger().Info("Failed to load game tables from app setting"); } var tables = GetGameTables(); if (tables.Count <= 0) { node.GetLogger().Info("No game table created from app setting"); } else { node.GetLogger().Info(tables.Count + " game table(s) created from app setting"); foreach (var gameTable in tables) { node.GetLogger().Info("--------------------------------------"); node.GetLogger().Info("Table Code: " + gameTable.TableCode); node.GetLogger().Info("Betting Time: " + gameTable.TimeToBet); node.GetLogger().Info("Test Merchant Code: " + gameTable.TestMerchant); await gameTable.Open(); } node.GetLogger().Info("--------------------------------------"); } await Task.Delay(100); node.GetLogger().Info(this.GetType().Name + " started"); return(""); }