| #!/usr/bin/python  | 
| # -*- coding: GBK -*-  | 
| #  | 
| # @todo:   | 
| #  | 
| # @author: Alee  | 
| # @date 2018-1-3 ÏÂÎç05:47:38  | 
| # @version 1.0  | 
| #  | 
| # @note:   | 
| #  | 
| #---------------------------------------------------------------------  | 
|   | 
| #ϵͳ  | 
| import os  | 
| import sys  | 
| import time  | 
| import datetime  | 
| from binary.PyNetwork import *  | 
| from threading import Thread  | 
| import logging  | 
| from DataReader import MapEventPointReader, ChinMapReader  | 
|   | 
| import ConfigurationReader.RobotsConfigReader  | 
| import ConfigurationReader.ConfigIniReader   | 
| from Robot.RobotMgr import *  | 
|   | 
| import traceback  | 
| import base64  | 
| import pymongo  | 
| import datetime  | 
|   | 
|   | 
| ServerDBConfigPath1 = r"\Config\config.ini"  | 
| ServerDBConfigPath2 = r"\PyMongoDataServer.ini"  | 
|   | 
| g_starttime = time.time()  | 
|   | 
| BASE64_ENCODE_CNT = 3  | 
| XOR_KEY = 151  | 
| def GetEncodePsw(psw):  | 
|     ret = ""  | 
|     try:  | 
|         for i in range(BASE64_ENCODE_CNT):  | 
|             psw = base64.decodestring(psw)  | 
|     except:  | 
|   | 
|         return False,ret  | 
|       | 
|     for i in psw:  | 
|         ret += chr(ord(i)^XOR_KEY)  | 
|     return True, ret  | 
|   | 
| TYPE_Time_Format = "%Y-%m-%d %H:%M:%S"  | 
| def GetDateTimeByStr(timeStr):  | 
|     timeStr = timeStr.strip().split(".")[0]  | 
|     try:  | 
|         return  datetime.datetime.strptime(timeStr, TYPE_Time_Format)  | 
|     except BaseException , e :  | 
|         return  | 
|   | 
|     return  | 
|   | 
| def ChangeTimeStrToNum(timeStr, timeFormat=TYPE_Time_Format):  | 
|     timeStr = datetime.datetime.strptime(timeStr, timeFormat).timetuple()   | 
|     return int(time.mktime(timeStr))   | 
|   | 
|   | 
| # Êý¾Ý¿â¹ÜÀí  | 
| class MongoDBRobot():  | 
|     def __init__(self):  | 
|         self.user = ""  | 
|         self.pwd = ""  | 
|         self.dbIP = ""  | 
|         self.dbName = ""  | 
|           | 
|         self.logdb = None  | 
|         self.interfaceDatadb = None  | 
|         self.userdb = None  | 
|         self.connection = None  | 
|       | 
|         config =  ConfigurationReader.ConfigIniReader.GetConfig()  | 
|           | 
|         self.PlayerOffTime = config.GetPlayerOffTime() #Íæ¼ÒÏÂÏßʱ³¤  | 
|         self.ServerDBConfigPath = config.GetServerDBConfigPath()    #Êý¾Ý¿â·¾¶  | 
|         self.InitDBCon()  | 
|           | 
|         self.tokenList = []   # Êý¾Ý¿â»ñÈ¡£¬µÇ¼ȥ³ý  | 
|           | 
|           | 
|     def InitDBCon(self):  | 
|         dbConfig = ConfigurationReader.ConfigIniReader.AppConfig(self.ServerDBConfigPath + ServerDBConfigPath1)  | 
|         dbConfig.SetSection( "auth" )  | 
|         self.user = dbConfig.GetValue("logdb_user")  | 
|         self.pwd = GetEncodePsw(dbConfig.GetValue("logdb_pwd"))[1]  | 
|           | 
|         dbConfig2 = ConfigurationReader.ConfigIniReader.AppConfig(self.ServerDBConfigPath + ServerDBConfigPath2)  | 
|         dbConfig2.SetSection( "connect" )  | 
|         self.dbIP = dbConfig2.GetValue("LOG_DB_IP")  | 
|         self.connection = pymongo.Connection(self.dbIP, 27017, auto_start_request=False)  | 
|         db = self.connection.admin  | 
|         if not db.authenticate(self.user, self.pwd):  | 
|             logging.error( "!!!InitDBCon error" )  | 
|             return  | 
|           | 
|         #print dbConfig2.GetValue("LOG_DB_NAME"), "--------------"  | 
|           | 
|         self.logdb = self.connection[dbConfig2.GetValue("LOG_DB_NAME")]  | 
|         #self.interfaceDatadb = self.connection[dbConfig2.GetValue("INTERFACE_DB_NAME")]  | 
|         self.userdb = self.connection[dbConfig2.GetValue("USER_DB_NAME")]  | 
|           | 
|         logging.info("conn ok-----------")  | 
|           | 
|     # 1.»ñÈ¡ÍÑ»ú¹ÒÍæ¼ÒÊý¾Ý--GameLog  | 
|     def GetTJGRobot(self):  | 
|         col = self.logdb["tagDBPlayerInfoLog"]  | 
|         # Õý³£ºÅÏÂÏß³¬¹ý3·ÖÖÓ£¬ÓÐÍÑ»ú¹Òʱ¼ä²¢ÇÒÍÑ»ú¹Ò״̬·Ç2µÄÇé¿ö  | 
|         # 1ΪÍÑ»ú¹ÒʱÒì³£µôÏߣ¬Ó¦¿ÉÁ¢¼´ÍÑ»úÖØÁ¬£¬Ä¿Ç°¶¼°´¶ÏÏß3·ÖÖÓºóÖØÁ¬  | 
|         # 2ΪÍÑ»ú¹ÒµÄʱºò±»ÈËɱËÀ£¬µÈ´ýÍæ¼ÒÖ÷¶¯µÇ½  | 
|         nowTime = time.time()  | 
|         offTime = nowTime - self.PlayerOffTime  | 
|   | 
|         resultSet = col.find({"IsOnline":0, "LastLogoffTime":{"$lt":offTime}, "AccState":1,   | 
|                              "TJGTime":{"$gt":0}, "TJGState":{"$lt":2}})  | 
|         if not resultSet:  | 
|             return  | 
|         accIDList = []  | 
|           | 
|         for robot in resultSet:  | 
|             accIDList.append(str(robot["AccID"]))  | 
|               | 
|         #print "gamelog ----ÀëÏß", accIDList  | 
|         # »ñÈ¡token  | 
| #===============================================================================  | 
| #        col= self.interfaceDatadb["tagLoginInfo"]  | 
| #        for accID in accIDList:  | 
| #            result = col.find_one({"qid":accID})  | 
| #            if not result:  | 
| #                continue  | 
| #   | 
| #            loginTime = int(result["time"])  | 
| #            if nowTime - loginTime < 10:  | 
| #                # ¹ýÂËÕýÔڵǼÖеÄÕ˺Å, ÊÖ»úÖØµÇÐè¸üÐÂtime  | 
| #                continue  | 
| #              | 
| #            # Êý¾Ý¿âÈ¡³öΪunicode  | 
| #            clientMac = ""  | 
| #            if "clientmac" in result:  | 
| #                clientMac = str(result['clientmac'][0])  | 
| #            else:  | 
| #                logging.debug( "-----Íæ¼ÒµÇ¼һ°ë¶Ï¿ª-------------")  | 
| #              | 
| #            account = (str(result["sign"]), str(result["qid"]), clientMac)  | 
| #            if account not in self.tokenList:  | 
| #                self.tokenList.append(account)  | 
| #===============================================================================  | 
|               | 
|         # »ñÈ¡token, ×ÔÓÉSDK tokenÔÚuser¿â  | 
|         col= self.userdb["tagDSAccount"]  | 
|         for accID in accIDList:  | 
|             result = col.find_one({"ACCID":accID})  | 
|             if not result:  | 
|                 continue  | 
|               | 
|             timeStr = result["LastLoginTime"]  | 
|             if not timeStr:  | 
|                 continue  | 
|             loginTime = ChangeTimeStrToNum(timeStr)  | 
|             if nowTime - loginTime < 10:  | 
|                 # ¹ýÂËÕýÔڵǼÖеÄÕ˺Å, ÊÖ»úÖØµÇÐè¸üÐÂtime  | 
|                 continue  | 
|               | 
|             # Êý¾Ý¿âÈ¡³öΪunicode  | 
|             clientMac = "abc"  | 
|               | 
|             account = (str(result["Psw"]), accID, clientMac, int(result["Adult"]), str(result['AppID']))  | 
|             if account not in self.tokenList:  | 
|                 self.tokenList.append(account)  | 
|               | 
|               | 
|         if self.tokenList:  | 
|             logging.info( "´ýµÇ¼µÄÍÑ»ú¹ÒÍæ¼Ò----:%s"%(len(self.tokenList)))  | 
|             logging.debug( "´ýµÇ¼µÄÍÑ»ú¹ÒÍæ¼Ò----tokenList:%s"%(self.tokenList))  | 
|         return  | 
|       | 
|     def GetTokenList(self):  | 
|         return self.tokenList  | 
|       | 
|     def RemoveToken(self, value):  | 
|         self.tokenList.remove(value)  | 
|       | 
|     def ClearToken(self):  | 
|         self.tokenList = []  | 
|       | 
| class WorkerThread(Thread):  | 
|     def __init__(self, mgr, dbRobot ):  | 
|         Thread.__init__(self, None, None, "WorkerThreadPy")  | 
|         self.mgr = mgr  | 
|         self.dbRobot = dbRobot  | 
|           | 
|         self.lastTime = 0  | 
|         config =  ConfigurationReader.ConfigIniReader.GetConfig()  | 
|           | 
|         self.ProcessFindTJGTime = config.GetProcessFindTJGTime() #²éѯÊý¾Ý¿â¼ä¸ô  | 
|         self.StartRunTime = config.GetStartRunTime()    # ÔËÐÐºó¿ªÆôÍÑ»úµÇ¼µÄ¼ä¸ô  | 
|         self.lastStartRunTime = 0  | 
|           | 
|     def run(self):  | 
|         logging.debug( "thread %s start" % self.getName() )  | 
|         while 1:  | 
|             try:  | 
|                 #Ïß³Ì1 »ñÈ¡ÍÑ»ú¹ÒÍæ¼ÒÊý¾Ý£¬¼ÓÈëµ½robotmgr  | 
|                 self.mgr.ThreadRun()  | 
|                 time.sleep(0.02)  | 
|                   | 
|                 nowTime = time.time()  | 
|                 if self.lastStartRunTime == 0:  | 
|                     self.lastStartRunTime = nowTime  | 
|                   | 
|                 if nowTime - self.lastStartRunTime < self.StartRunTime:  | 
|                     #¿ªÆôÔËÐкóÒ»¶Îʱ¼äÄÚ²»½øÐÐÍÑ»úµÇ¼  | 
|                     continue  | 
|                   | 
|                 if nowTime - self.lastTime > self.ProcessFindTJGTime:  | 
|                     if nowTime - g_starttime > 40:  | 
|                         os.system('cls') # ÇåÆÁÄ»  | 
|                     print "-----", datetime.datetime.today()  | 
|                     self.dbRobot.GetTJGRobot()  | 
|                     self.lastTime = nowTime  | 
|                   | 
|                                               | 
|             except Exception, e:  | 
|                 print str(e)  | 
|                 print traceback.print_exc()  | 
|                 logging.error( "WorkerThread: %s"%str(e) )  | 
|                 logging.error( "WorkerThread: %s"%traceback.print_exc() )  | 
|               | 
|     # 1.»ñÈ¡ÍÑ»ú¹ÒÍæ¼ÒÊý¾Ý--GameLog  | 
|     # 2.³õʼ»¯ÍÑ»ú¹ÒÍæ¼ÒµÄrobot¼ÓÈëmgr  | 
|     # 3.ÇëÇóÐÂtokenµÇ¼--InterfaceData  | 
|     # 4.µÇ¼ºóÔÚ0107loadmapok°üǰ·¢ËÍÍÑ»úµÇ¼ÏûÏ¢£¬ÓÃÓÚÇø·ÖÍæ¼ÒÕæÊµµÇ¼  | 
|     # 5.ÍÑ»ú¹ÒÍæ¼Ò·À³ÁÃÔÂß¼ÐÞÕý£¬¸ù¾Ý4Ìõ¼þ  | 
|               | 
| def StartApp( PyBaseRoot ):  | 
|     logging.info( "PyBaseRoot:%s" % PyBaseRoot )  | 
|     os.system("title Robot-%s"%datetime.datetime.today())  | 
|       | 
|     #¶ÁÈ¡¸÷ÖÖÅäÖã¨IP£¬¶Ë¿Ú£¬VERSION_NOµÈ£©  | 
|     ConfigurationReader.ConfigIniReader.ReadConfig( PyBaseRoot + "Configuration\\Config.ini" )  | 
|     config =  ConfigurationReader.ConfigIniReader.GetConfig()  | 
|     #logging.info( "ConfigData:%s" % str(config) )  | 
|       | 
|     dbRobot = MongoDBRobot()  | 
|       | 
|     #¶ÁÈ¡¸÷ÖÖÊý¾Ý£¨µØÍ¼£©, ÍÑ»ú¹ÒÖ±½Ó·ÉÐÐ  | 
|     #MapDataReader.ReadMapData( PyBaseRoot )  | 
|     #TransportDataReader.ReadTransportData( PyBaseRoot )  | 
|     MapEventPointReader.ReadMapEventPoint(PyBaseRoot)  | 
|     ChinMapReader.ReadChinMapData(PyBaseRoot)  | 
|       | 
|     #³õʼ»¯ÍøÂ磨Asio£©  | 
|     asioMgr = CAsioMgr()  | 
|     ret = asioMgr.InitModule( config.GetVersionNo(), config.GetPackStartCount(),\  | 
|                               config.GetKeyString(), PyBaseRoot + config.GetSendKeyDictFilePath() )  | 
|     if not ret:  | 
|         logging.fatal( "Init PyNetwork failed." )  | 
|         return  | 
|     else:  | 
|         logging.debug( "Init PyNetwork success." )  | 
|        | 
|     #´´½¨ÍøÂçÄ£¿é¹¤×÷Ị̈߳¬ÕâЩÏß³ÌÊýÁ¿²»Ò˹ý¶à£¬ÒÔÃâ³öÏÖ´óÁ¿¾ºÕù    | 
|     #½¨Òéȡֵ·¶Î§ÔÚ nThreadsµ½2*nThreadsÖ®¼ä  | 
|     nThreads = asioMgr.GetProcessorNumber()  | 
|     logging.info( "Host has %d logic processor." % nThreads )  | 
|     th = WorkerThread( asioMgr, dbRobot )  | 
|     th.start()  | 
|           | 
|     #´´½¨RobotMgr£¬Ìṩ»úÆ÷ÈË×ÜÊý£¨´ËMgrÄÚ²¿»á´´½¨AIÏß³ÌÓÃÓÚ½øÐÐAI´¦Àí£©  | 
|     CreateRobotMgr( asioMgr, dbRobot)  | 
|   | 
|       | 
|      |