Exemplo n.º 1
0
        public int Update(dynamic bet)
        {
            //System.Diagnostics.Debugger.Break();

            //m_Logger.Info("Settle bet - " + bet.bet_uuid);

            int ret = 0;

            var dbhelper = m_Node.GetDataHelper();

            using (var cnn = dbhelper.OpenDatabase(m_MainCache))
            {
                using (var cmd = cnn.CreateCommand())
                {
                    dbhelper.AddParam(cmd, "@bet_uuid", bet.bet_uuid);
                    dbhelper.AddParam(cmd, "@pay_amount", bet.pay_amount);
                    dbhelper.AddParam(cmd, "@game_result", bet.game_result);

                    cmd.CommandText = "update tbl_bet_record "
                                      + " set pay_amount = @pay_amount "
                                      + " , game_result = @game_result "
                                      + " , bet_state = 1 "
                                      + " , settle_time = CURRENT_TIMESTAMP "
                                      + " where bet_uuid = @bet_uuid "
                    ;
                    ret = cmd.ExecuteNonQuery();
                }
            }

            //m_Logger.Info("done");

            return(ret);
        }
Exemplo n.º 2
0
        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());
            }
        }
        private void UpdateLocalCacheFromDb()
        {
            Dictionary <string, dynamic> merchants = new Dictionary <string, dynamic>();

            var dbhelper = m_Node.GetDataHelper();

            using (var cnn = dbhelper.OpenDatabase(m_MainDatabase))
            {
                using (var cmd = cnn.CreateCommand())
                {
                    cmd.CommandText = " select * from tbl_merchant_info ";

                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var item = new
                            {
                                merchant = reader["merchant_code"].ToString(),
                                url      = reader["api_url"].ToString(),
                                active   = Convert.ToInt32(reader["is_active"].ToString())
                            };

                            if (merchants.ContainsKey(item.merchant))
                            {
                                merchants.Remove(item.merchant);
                            }
                            merchants.Add(item.merchant, item);
                        }
                    }
                }
            }

            m_Merchants = merchants;
        }
        public string ValidateRequest(RequestContext ctx)
        {
            string betstr = ctx.Data.ToString();

            if (betstr.Trim().Length <= 0)
            {
                return("Invalid request");
            }

            dynamic betreq = ctx.JsonHelper.ToJsonObject(betstr);

            string playerId     = betreq.player_id;
            string merchantCode = betreq.merchant_code;
            string sessionId    = betreq.session_id;

            var okay = false;

            if (!String.IsNullOrEmpty(merchantCode) &&
                !String.IsNullOrEmpty(playerId) &&
                !String.IsNullOrEmpty(sessionId))
            {
                var dbhelper = m_Node.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, "@player_id", playerId);

                        cmd.CommandText = " select * from tbl_player_session "
                                          + " where merchant_code = @merchant_code "
                                          + " and player_id = @player_id "
                                          + " and session_id = @session_id "
                        ;

                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                okay = true;
                            }
                        }
                    }
                }
            }

            if (!okay)
            {
                m_Node.GetLogger().Info("Invalid session: " + sessionId);
                return("Invalid session");
            }
            else
            {
                m_Node.GetLogger().Info("Bet session is ok: " + sessionId);
            }

            return("");
        }
Exemplo n.º 5
0
        public void Start()
        {
            Stop();

            m_Logger.Info("Clean up old cache...");
            Thread.Sleep(500);

            try
            {
                var dbhelper = m_Node.GetDataHelper();
                using (var cnn = dbhelper.OpenDatabase(m_MainCache))
                {
                    using (var cmd = cnn.CreateCommand())
                    {
                        dbhelper.AddParam(cmd, "@server_code", m_Node.GetName());
                        dbhelper.AddParam(cmd, "@table_code", TableCode);

                        cmd.CommandText = " delete from tbl_round_state "
                                          + " where server_code = @server_code ; ";
                        cmd.CommandText = cmd.CommandText + " delete from tbl_round_state "
                                          + " where table_code = @table_code ; ";

                        cmd.ExecuteNonQuery();
                    }
                }

                Thread.Sleep(500);
                m_Logger.Info("Done");
            }
            catch (Exception ex)
            {
                m_Logger.Error("Failed to clean up old cache: ");
                m_Logger.Error(ex.ToString());
            }


            m_RoundIndex = 0;
            //m_GameCode = Guid.NewGuid().ToString();
            m_ShoeCode = DateTime.Now.ToString("yyyyMMddHHmmss");
            m_History.Clear();
            m_GameReadyCountdown = GET_READY_COUNTDOWN;
            m_GameState          = GAME_STATUS.GetGameReady;
            m_WaitingForDealing  = false;
            m_IsRunningGameLoop  = false;
            m_Timer = new Timer(Tick, m_Rng, 500, 1000 * 1);
        }
        public async Task <string> Load(IServerNode node)
        {
            //System.Diagnostics.Debugger.Break();

            m_BaseBetCode = Guid.NewGuid().ToString();

            node.GetLogger().Info("Reloading database settings from config...");

            await Task.Delay(50);

            // we can apply new merchant db config just by hot-swapping, no need to restart server
            node.GetDataHelper().RefreshDatabaseSettings();
            await Task.Delay(50);

            node.GetLogger().Info(this.GetType().Name + " service started");

            return("");
        }
        private void UpdateLocalCacheFromDb()
        {
            Dictionary <string, dynamic> merchants = new Dictionary <string, dynamic>();

            var dbhelper = m_Node.GetDataHelper();

            using (var cnn = dbhelper.OpenDatabase(m_MainDatabase))
            {
                using (var cmd = cnn.CreateCommand())
                {
                    cmd.CommandText = " select * from tbl_merchant_info ";

                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var item = new
                            {
                                merchant    = reader["merchant_code"].ToString(),
                                currency    = reader["currency_code"].ToString(),
                                url         = reader["api_url"].ToString(),
                                db          = reader["db_name"].ToString(),
                                cpc         = reader["cpc_options"].ToString(),
                                bpl         = reader["bpl_options"].ToString(),
                                active      = Convert.ToInt32(reader["is_active"].ToString()),
                                service     = reader["api_service"].ToString(),
                                maintaining = Convert.ToInt32(reader["is_maintained"].ToString())
                            };

                            string merchantKey = item.merchant + item.currency;

                            if (merchants.ContainsKey(merchantKey))
                            {
                                merchants.Remove(merchantKey);
                            }
                            merchants.Add(merchantKey, item);
                        }
                    }
                }
            }

            m_Merchants = merchants;
        }
        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();
            }
        }
Exemplo n.º 9
0
        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
                           }
                };
            }
        }
    }
Exemplo n.º 11
0
        public string ValidateRequest(RequestContext ctx)
        {
            //System.Diagnostics.Debugger.Break();

            string reqstr = ctx.Data.ToString();

            if (reqstr.Trim().Length <= 0)
            {
                return("Invalid request");
            }

            var okay = false;

            try
            {
                dynamic req          = ctx.JsonHelper.ToJsonObject(reqstr);
                string  playerId     = req.player_id;
                string  merchantCode = req.merchant_code;
                string  currencyCode = req.currency_code;
                string  sessionId    = req.session_id;
                string  clientToken  = req.client_token;

                if (!String.IsNullOrEmpty(merchantCode) &&
                    !String.IsNullOrEmpty(currencyCode) &&
                    !String.IsNullOrEmpty(playerId) &&
                    !String.IsNullOrEmpty(sessionId) &&
                    !String.IsNullOrEmpty(clientToken))
                {
                    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);
                            dbhelper.AddParam(cmd, "@client_token", clientToken);

                            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 "
                                              + " and client_token = @client_token "
                            ;

                            using (var reader = cmd.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    okay = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                okay = false;
                ctx.Logger.Error("Exception found when check front-end session: " + ex.Message);
            }

            if (!okay)
            {
                ctx.Logger.Error("Failed to check front-end session");
                return("Invalid or expired front-end session");
            }

            return("");
        }
Exemplo n.º 12
0
        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 count        = 0;
            var playerId     = "";
            var merchantCode = "";
            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)
                {
                    playerId = part;
                }
                if (count == 3)
                {
                    sessionId = part;
                }
                if (count > 3)
                {
                    break;
                }
            }

            var okay = false;

            if (!String.IsNullOrEmpty(merchantCode) &&
                !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, "@player_id", playerId);

                        cmd.CommandText = " select * from tbl_player_session "
                                          + " where merchant_code = @merchant_code "
                                          + " and player_id = @player_id "
                                          + " and session_id = @session_id "
                        ;

                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                okay = true;
                            }
                        }
                    }
                }
            }

            if (okay)
            {
                m_LocalNode.GetLogger().Info("Client session is ok: " + sessionId);
            }
            else
            {
                m_LocalNode.GetLogger().Info("Invalid session: " + sessionId);
            }

            if (okay && m_Deliverer != null)
            {
                m_Deliverer.AddClient(session.GetRemoteAddress(), session);
            }
            else
            {
                session.CloseConnection();
            }
        }
Exemplo n.º 13
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 List <dynamic> CheckBetWinlossByGameResult(string gameServer)
        {
            //System.Diagnostics.Debugger.Break();

            m_Logger.Info("CheckBetWinlossByGameResult - " + gameServer);

            List <dynamic> bets = new List <dynamic>();

            Dictionary <string, decimal> payouts   = new Dictionary <string, decimal>();
            Dictionary <string, int>     results   = new Dictionary <string, int>();
            Dictionary <string, string>  merchants = new Dictionary <string, string>();
            Dictionary <string, string>  players   = new Dictionary <string, string>();
            Dictionary <string, int>     pools     = new Dictionary <string, int>();
            var dbhelper = m_Node.GetDataHelper();

            using (var cnn = dbhelper.OpenDatabase(m_MainCache))
            {
                using (var cmd = cnn.CreateCommand())
                {
                    dbhelper.AddParam(cmd, "@server_code", gameServer);

                    cmd.CommandText = " select a.game_result, b.bet_uuid, b.merchant_code, b.player_id, b.bet_pool, b.bet_amount from tbl_round_state a, tbl_bet_record b "
                                      + " where a.round_state = 9 and b.bet_state = 0 "
                                      + " and a.server_code = @server_code "
                                      + " and a.server_code = b.server_code "
                                      + " and a.table_code = b.table_code "
                                      + " and a.shoe_code = b.shoe_code "
                                      + " and a.round_number = b.round_number "
                    ;
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string  result   = reader["game_result"].ToString();
                            string  betGuid  = reader["bet_uuid"].ToString();
                            string  merchant = reader["merchant_code"].ToString();
                            string  player   = reader["player_id"].ToString();
                            int     pool     = Convert.ToInt32(reader["bet_pool"].ToString());
                            decimal amount   = Convert.ToDecimal(reader["bet_amount"].ToString());

                            if (payouts.ContainsKey(betGuid))
                            {
                                continue;
                            }

                            merchants.Add(betGuid, merchant);
                            players.Add(betGuid, player);
                            pools.Add(betGuid, pool);

                            if (result[0] == '1' && pool == 1)
                            {
                                payouts.Add(betGuid, amount * m_PayRates["B"]);
                            }
                            else if (result[0] == '2' && pool == 2)
                            {
                                payouts.Add(betGuid, amount * m_PayRates["P"]);
                            }
                            else if (result[0] == '3' && pool == 3)
                            {
                                payouts.Add(betGuid, amount * m_PayRates["T"]);
                            }
                            else if (result[0] == '3' && (pool == 1 || pool == 2))
                            {
                                payouts.Add(betGuid, amount);                                                    // zero winloss
                            }
                            else
                            {
                                payouts.Add(betGuid, 0);  // lose
                            }
                            results.Add(betGuid, Convert.ToInt32(result));
                        }
                    }
                }

                if (payouts.Count <= 0)
                {
                    return(bets);
                }

                foreach (var item in payouts)
                {
                    dynamic bet = new
                    {
                        bet_uuid      = item.Key,
                        pay_amount    = item.Value,
                        game_result   = results[item.Key],
                        bet_pool      = pools[item.Key],
                        merchant_code = merchants[item.Key],
                        player_id     = players[item.Key]
                    };

                    bets.Add(bet);
                }

                return(bets);
            }
        }
        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"
            }));
        }