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));
        }
示例#2
0
        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("");
        }
        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
                           }
                };
            }
        }
    }
示例#4
0
        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 PlayerLogin(RequestContext ctx)
        {
            string reqstr = ctx.Data.ToString();

            if (reqstr.Trim().Length <= 0)
            {
                await ctx.Session.Send(ctx.JsonHelper.ToJsonString(new
                {
                    error_code    = -1,
                    error_message = "Invalid request"
                }));

                return;
            }

            dynamic req = ctx.JsonHelper.ToJsonObject(reqstr);

            string merchantUrl = await RemoteCaller.RandomCall(m_LocalNode.GetRemoteServices(),
                                                               "merchant-data", "get-merchant-url", req.merchant_code.ToString());

            if (String.IsNullOrEmpty(merchantUrl))
            {
                await ctx.Session.Send(ctx.JsonHelper.ToJsonString(new
                {
                    error_code    = -1,
                    error_message = "Merchant API URL not found: " + req.merchant_code.ToString()
                }));

                return;
            }

            ctx.Logger.Info("Player login - [" + req.merchant_code.ToString() + "] " + req.player_id.ToString());
            ctx.Logger.Info("Merchant URL - " + merchantUrl);

            var apiReq = new
            {
                req.merchant_code,
                req.player_id,
                req.login_token
            };
            dynamic ret = await RemoteCaller.Request(merchantUrl + "/player/validate-login", apiReq, null, 10 * 1000);

            if (ret == null || ret.error_code != 0)
            {
                ctx.Logger.Error("Three-Way Login Error: " + (ret == null ? "Failed to call merchant API" : ret.error_message));
                await ctx.Session.Send(ctx.JsonHelper.ToJsonString(new
                {
                    error_code    = -1,
                    error_message = "Three-Way Login Error"
                }));

                return;
            }

            var okay      = false;
            var sessionId = Guid.NewGuid().ToString();

            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", req.merchant_code);
                    dbhelper.AddParam(cmd, "@player_id", req.player_id);

                    cmd.CommandText = " update tbl_player_session "
                                      + " set session_id = @session_id , update_time = NOW() "
                                      + " where merchant_code = @merchant_code and player_id = @player_id ";

                    okay = cmd.ExecuteNonQuery() > 0;

                    if (!okay)
                    {
                        using (var cmd2 = cnn.CreateCommand())
                        {
                            dbhelper.AddParam(cmd2, "@session_id", sessionId);
                            dbhelper.AddParam(cmd2, "@merchant_code", req.merchant_code);
                            dbhelper.AddParam(cmd2, "@player_id", req.player_id);

                            cmd2.CommandText = " insert into tbl_player_session "
                                               + " ( session_id , merchant_code, player_id, update_time ) values "
                                               + " ( @session_id, @merchant_code, @player_id, NOW() ) ";

                            okay = cmd2.ExecuteNonQuery() > 0;
                        }
                    }
                }
            }

            if (!okay)
            {
                ctx.Logger.Error("Three-Way Login Failed!");
                await ctx.Session.Send(ctx.JsonHelper.ToJsonString(new
                {
                    error_code    = -1,
                    error_message = "Three-Way Login Failed"
                }));

                return;
            }

            var remoteServices = m_LocalNode.GetRemoteServices();

            var frontEndUrl  = RandomPickPublicServiceUrl(remoteServices, "table-info");
            var betServerUrl = RandomPickPublicServiceUrl(remoteServices, "accept-bet");

            await ctx.Session.Send(ctx.JsonHelper.ToJsonString(new
            {
                req.merchant_code,
                req.player_id,
                ret.player_balance,
                session_id    = sessionId,
                front_end     = frontEndUrl,
                bet_server    = betServerUrl,
                error_code    = 0,
                error_message = "Three-Way Login Okay"
            }));
        }