hxp
2018-08-10 ccfc87e02e2ae7d153bbab0754639a1a663d34d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/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"]))
            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)
    
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)