def _exec(req, data=None, showLog=True, api=XVM.API_VERSION, params={}): url = None response = None errStr = None try: url = XVM.SERVERS[randint(0, len(XVM.SERVERS) - 1)] url = url.format(API=api, REQ=req) for k, v in params.iteritems(): url = url.replace('{' + k + '}', '' if v is None else str(v)) accountDBID = utils.getAccountDBID() if accountDBID is None: accountDBID = 0 token = config.token.token if token is None: token = '-' url = url.format(id=accountDBID, token=token) (response, duration, errStr) = loadUrl(url, body=data) return (None if not response else unicode_to_ascii( simplejson.loads(response)), errStr) except Exception as ex: err(traceback.format_exc()) err('url = {}'.format(utils.hide_guid(url))) err('response = {}'.format(utils.hide_guid(response))) err('errStr = {}'.format(utils.hide_guid(errStr))) return (None, sys.exc_info()[0])
def _exec(req, data=None, showLog=True, api=XVM.API_VERSION, params={}): url = None response = None errStr = None try: url = XVM.SERVERS[randint(0, len(XVM.SERVERS) - 1)] url = url.format(API=api, REQ=req) for k, v in params.iteritems(): url = url.replace('{'+k+'}', '' if v is None else str(v)) accountDBID = utils.getAccountDBID() if accountDBID is None: accountDBID = 0 token = config.token.token if token is None: token = '' url = url.format(id=accountDBID, token=token) (response, duration, errStr) = loadUrl(url, None, data) return (None if not response else unicode_to_ascii(simplejson.loads(response)), errStr) except Exception as ex: err(traceback.format_exc()) err('url = {}'.format(utils.hide_guid(url))) err('response = {}'.format(utils.hide_guid(response))) err('errStr = {}'.format(utils.hide_guid(errStr))) return (None, sys.exc_info()[0])
def _initializeXvmToken(): #debug('_initializeXvmToken') global _tdataPrev clearToken() # use last player id for replays playerId = getCurrentPlayerId() if not isReplay() else userprefs.get('tokens.lastPlayerId') if playerId is None: return tdataActive = _getXvmActiveTokenData() (tdata, errStr) = _checkToken(playerId, None if tdataActive is None else tdataActive['token']) if tdata is None: tdata = _tdataPrev if not isReplay(): type = SystemMessages.SM_TYPE.Warning msg = _getXvmMessageHeader() if tdata is None: msg += '{{l10n:token/services_unavailable}}\n\n%s' % utils.hide_guid(errStr) elif tdata['status'] == 'badToken' or tdata['status'] == 'inactive': msg += '{{l10n:token/services_inactive}}' elif tdata['status'] == 'blocked': msg += '{{l10n:token/blocked}}' elif tdata['status'] == 'active': type = SystemMessages.SM_TYPE.GameGreeting msg += '{{l10n:token/active}}\n' s = time.time() e = tdata['expires_at'] / 1000 days_left = int((e - s) / 86400) hours_left = int((e - s) / 3600) % 24 mins_left = int((e - s) / 60) % 60 token_name = 'time_left' if days_left >= 3 else 'time_left_warn' msg += '{{l10n:token/%s:%d:%02d:%02d}}\n' % (token_name, days_left, hours_left, mins_left) msg += '{{l10n:token/cnt:%d}}' % tdata['cnt'] else: type = SystemMessages.SM_TYPE.Error msg += '{{l10n:token/unknown_status}}\n%s' % utils.hide_guid(simplejson.dumps(tdata)) msg += '</textformat>' if _tdataPrev is None or _tdataPrev['status'] != 'active' or tdata is None or tdata['status'] != 'active': g_eventBus.handleEvent(events.HasCtxEvent(XVM_EVENT.SYSTEM_MESSAGE, {'msg':msg,'type':type})) if tdata is not None: _tdataPrev = tdata if tdata['status'] == 'active': if 'token' not in tdata and tdataActive is not None: tdata['token'] = tdataActive['token'] else: if 'token' in tdata: del tdata['token'] userprefs.set('tokens.{0}'.format(playerId), tdata) userprefs.set('tokens.lastPlayerId', playerId) global networkServicesSettings networkServicesSettings = _makeNetworkServicesSettings(tdata) global _token _token = '' if tdata is None else tdata.get('token', '').encode('ascii')
def _checkToken(playerId, token): data = None errStr = None try: req = "checkToken/%d" % playerId if token is not None: req += "/%s" % token.encode('ascii') server = XVM.SERVERS[randint(0, len(XVM.SERVERS) - 1)] (response, duration, errStr) = loadUrl(server, req) # response= """{"status":"inactive"}""" # response = """{"expires_at":1394834790589,"cnt":0,"_id":4630209,"status":"active", # "token":"84a45576-5f06-4945-a607-bbee61b4876a","__v":0,"start_at":1393625190589}""" # response = """{"expires_at":1394817931657,"cnt":3,"_id":2178413,"status":"badToken", # "start_at":1393608331657}""" if not response: # err('Empty response or parsing error') pass else: try: if response is None: return None response = response.strip() data = None if response in ('', '[]') else simplejson.loads(response) log(utils.hide_guid(response)) except Exception, ex: errStr = 'Bad answer: ' + response err(' ' + errStr) data = None except Exception, ex: errStr = str(ex) err(traceback.format_exc())
def tokenUpdated(): type = SystemMessages.SM_TYPE.Warning msg = _getXvmMessageHeader() status = config.token.status if status is None: msg += '{{l10n:token/services_unavailable}}\n\n%s' % utils.hide_guid(config.token.errStr) elif status == 'badToken' or status == 'inactive': msg += '{{l10n:token/services_inactive}}' elif status == 'blocked': msg += '{{l10n:token/blocked}}' elif status == 'active': type = SystemMessages.SM_TYPE.GameGreeting msg += '{{l10n:token/active}}\n' s = time.time() e = config.token.expires_at / 1000 days_left = int((e - s) / 86400) hours_left = int((e - s) / 3600) % 24 mins_left = int((e - s) / 60) % 60 token_name = 'time_left' if days_left >= 11 else 'time_left_warn' msg += '{{l10n:token/%s:%d:%02d:%02d}}' % (token_name, days_left, hours_left, mins_left) else: type = SystemMessages.SM_TYPE.Error msg += '{{l10n:token/unknown_status}}\n%s' % status msg += '</textformat>' g_eventBus.handleEvent(events.HasCtxEvent(XVM_EVENT.SYSTEM_MESSAGE, {'msg':msg,'type':type}))
def tokenUpdated(): type = SystemMessages.SM_TYPE.Warning msg = _getXvmMessageHeader() status = config.token.status if status is None: msg += '{{l10n:token/services_unavailable}}\n\n%s' % utils.hide_guid( config.token.errStr) elif status == 'badToken' or status == 'inactive': msg += '{{l10n:token/services_inactive}}' elif status == 'blocked': msg += '{{l10n:token/blocked}}' elif status == 'active': type = SystemMessages.SM_TYPE.GameGreeting msg += '{{l10n:token/active}}\n' s = time.time() e = config.token.expires_at / 1000 days_left = int((e - s) / 86400) hours_left = int((e - s) / 3600) % 24 mins_left = int((e - s) / 60) % 60 token_name = 'time_left' if days_left >= 11 else 'time_left_warn' msg += '{{l10n:token/%s:%d:%02d:%02d}}' % (token_name, days_left, hours_left, mins_left) else: type = SystemMessages.SM_TYPE.Error msg += '{{l10n:token/unknown_status}}\n%s' % status msg += '</textformat>' g_eventBus.handleEvent( events.HasCtxEvent(XVM_EVENT.SYSTEM_MESSAGE, { 'msg': msg, 'type': type }))
def loadUrl(url, req=None, body=None, content_type='text/plain; charset=utf-8', showLog=True, api=XVM.API_VERSION): url = url.replace("{API}", api) if req is not None: url = url.replace("{REQ}", req) u = urlparse(url) ssl = url.lower().startswith('https://') if showLog: # hide some chars of token in the log path_log = utils.hide_guid(u.path) if not XFW_NO_TOKEN_MASKING else u.path log(' HTTP%s: %s%s' % ('S' if ssl else '', path_log, '?' + u.query if u.query else ''), '[INFO] ') startTime = datetime.datetime.now() #import time #time.sleep(3) (response, compressedSize, errStr) = _loadUrl(u, XVM.TIMEOUT, body, content_type) # repeat request on timeout if errStr is not None and 'timed out' in errStr: (response, compressedSize, errStr) = _loadUrl(u, XVM.TIMEOUT, body, content_type) elapsed = datetime.datetime.now() - startTime msec = elapsed.seconds * 1000 + elapsed.microseconds / 1000 duration = None if response: if showLog: log(" Time: %d ms, Size: %d (%d) bytes" % (msec, compressedSize, len(response)), '[INFO] ') # debug('response: ' + response) if not response.lower().startswith('onexception'): duration = msec return (response, duration, errStr)
def loadUrl(url, req=None, body=None, showLog=True, api=XVM.API_VERSION): url = url.replace("{API}", api) if req is not None: url = url.replace("{REQ}", req) u = urlparse(url) ssl = url.lower().startswith('https://') if showLog: # hide some chars of token in the log path_log = utils.hide_guid(u.path) if not XFW_NO_TOKEN_MASKING else u.path log(' HTTP%s: %s' % ('S' if ssl else '', path_log), '[INFO] ') startTime = datetime.datetime.now() #import time #time.sleep(3) (response, compressedSize, errStr) = _loadUrl(u, XVM.TIMEOUT, XVM.FINGERPRINTS, body) elapsed = datetime.datetime.now() - startTime msec = elapsed.seconds * 1000 + elapsed.microseconds / 1000 duration = None if response: if showLog: log(" Time: %d ms, Size: %d (%d) bytes" % (msec, compressedSize, len(response)), '[INFO] ') # debug('response: ' + response) if not response.lower().startswith('onexception'): duration = msec return (response, duration, errStr)
def _checkToken(playerId, token): data = None try: req = "checkToken/%d" % playerId if token is not None: req += "/%s" % token.encode('ascii') server = XVM_STAT_SERVERS[randint(0, len(XVM_STAT_SERVERS) - 1)] (response, duration) = loadUrl(server, req) #response = """{"expires_at":1394834790589,"cnt":0,"_id":4630209,"status":"active","token":"84a45576-5f06-4945-a607-bbee61b4876a","__v":0,"start_at":1393625190589}""" #response = """{"expires_at":1394817931657,"cnt":1,"_id":2178413,"status":"inactive","start_at":1393608331657}""" #response = """{"expires_at":1394817931657,"cnt":3,"_id":2178413,"status":"badToken","start_at":1393608331657}""" if not response: #err('Empty response or parsing error') pass else: try: if response is None: return None response = response.strip() data = None if response in ('', '[]') else json.loads(response) log(utils.hide_guid(response)) except Exception, ex: err(' Bad answer: ' + response) data = None except Exception, ex: err(traceback.format_exc())
def loadUrl(url, req=None): url = url.replace("{API}", XVM_STAT_API_VERSION) if req is not None: url = url.replace("{REQ}", req) u = urlparse(url) ssl = url.lower().startswith('https://') # hide some chars of token in the log path_log = utils.hide_guid(u.path) log(' HTTP%s: %s' % ('S' if ssl else '', path_log), '[INFO] ') #time.sleep(5) startTime = datetime.datetime.now() (response, compressedSize) = _loadUrl(u, XVM_STAT_TIMEOUT, XVM_STAT_FINGERPRINT) elapsed = datetime.datetime.now() - startTime msec = elapsed.seconds * 1000 + elapsed.microseconds / 1000 if response: log(" Time: %d ms, Size: %d (%d) bytes" % (msec, compressedSize, len(response)), '[INFO] ') #debug('response: ' + response) if not response.lower().startswith('onexception'): duration = msec else: duration = None return (response, duration)
def loadUrl(url, req=None): url = url.replace("{API}", XVM_STAT_API_VERSION) if req is not None: url = url.replace("{REQ}", req) u = urlparse(url) ssl = url.lower().startswith('https://') # hide some chars of token in the log path_log = utils.hide_guid(u.path) log(' HTTP%s: %s' % ('S' if ssl else '', path_log), '[INFO] ') #time.sleep(5) startTime = datetime.datetime.now() (response, compressedSize) = _loadUrl(u, XVM_STAT_TIMEOUT, XVM_STAT_FINGERPRINT) elapsed = datetime.datetime.now() - startTime msec = elapsed.seconds * 1000 + elapsed.microseconds / 1000 if response: log( " Time: %d ms, Size: %d (%d) bytes" % (msec, compressedSize, len(response)), '[INFO] ') #debug('response: ' + response) if not response.lower().startswith('onexception'): duration = msec else: duration = None return (response, duration)
def onSystemMessage(self, e=None, cnt=0): #trace('onSystemMessage') msg = e.ctx.get('msg', '') type = e.ctx.get('type', SystemMessages.SM_TYPE.Information) if type not in [ SystemMessages.SM_TYPE.Information, SystemMessages.SM_TYPE.GameGreeting ]: log('SystemMessage: [{}] {}'.format(type, utils.hide_guid(msg))) SystemMessages.pushMessage(msg, type)
def _loadUrl(u, timeout, body, content_type): # timeout in msec response = None compressedSize = None errStr = None conn = None try: #log(u) cls = httplib.HTTPSConnection if u.scheme.lower() == 'https' else httplib.HTTPConnection global _proxy #log(_proxy) if _proxy: conn = cls(_proxy.hostname, _proxy.port, timeout=timeout/1000) headers = {} if _proxy.username and _proxy.password: auth = '%s:%s' % (_proxy.username, _proxy.password) headers['Proxy-Authorization'] = 'Basic ' + base64.b64encode(auth) #log(headers) conn.set_tunnel(u.hostname, u.port, headers=headers) else: conn = cls(u.netloc, timeout=timeout/1000) global _USER_AGENT headers = { "User-Agent": _USER_AGENT, "Accept-Encoding": "gzip", "Content-Type": content_type} conn.request("POST" if body else "GET", u.path + ('?' + u.query if u.query else ''), body, headers) resp = conn.getresponse() # log(resp.status) response = resp.read() compressedSize = len(response) encoding = resp.getheader('content-encoding') if encoding is None: pass # leave response as is elif encoding == 'gzip': response = gzip.GzipFile(fileobj=StringIO.StringIO(response)).read() else: raise Exception('Encoding not supported: %s' % encoding) # log(response) if resp.status not in [200, 202, 204, 401]: # 200 OK, 202 Accepted, 204 No Content m = re.search(r'<body[^>]+?>\r?\n?(.+?)</body>', response, flags=re.S | re.I) if m: response = m.group(1) response = re.sub(r'<[^>]+>', '', response) response = re.sub(r'nginx/\d+\.\d+\.\d+', '', response) response = response.strip() raise Exception('HTTP Error: [%i] %s. Response: %s' % (resp.status, resp.reason, response[:256])) except Exception as ex: response = None errStr = str(ex) if not isinstance(errStr, unicode): errStr = errStr.decode(locale.getdefaultlocale()[1]).encode("utf-8") # log(errStr) tb = traceback.format_exc(1).split('\n') err('loadUrl failed: %s%s' % (utils.hide_guid(errStr), tb[1])) finally: if conn is not None: conn.close() return (response, compressedSize, errStr)
def _loadUrl(u, timeout, fingerprints, body): # timeout in msec response = None compressedSize = None errStr = None conn = None try: # log(u) if u.scheme.lower() == 'https': checker = tlslite.CheckerXfw(x509Fingerprint=fingerprints) if fingerprints else None conn = tlslite.HTTPTLSConnection(u.netloc, timeout=timeout / 1000, checker=checker) else: conn = httplib.HTTPConnection(u.netloc, timeout=timeout / 1000) global _USER_AGENT headers = { "User-Agent": _USER_AGENT, "Connection": "Keep-Alive", "Accept-Encoding": "gzip", "Content-Type": "text/plain; charset=utf-8"} conn.request("POST" if body else "GET", u.path, body, headers) resp = conn.getresponse() # log(resp.status) response = resp.read() compressedSize = len(response) encoding = resp.getheader('content-encoding') if encoding is None: pass # leave response as is elif encoding == 'gzip': response = gzip.GzipFile(fileobj=StringIO.StringIO(response)).read() else: raise Exception('Encoding not supported: %s' % encoding) # log(response) if resp.status not in [200, 202, 204, 401]: # 200 OK, 202 Accepted, 204 No Content m = re.search(r'<body[^>]+?>\r?\n?(.+?)</body>', response, flags=re.S | re.I) if m: response = m.group(1) response = re.sub(r'<[^>]+>', '', response) response = re.sub(r'nginx/\d+\.\d+\.\d+', '', response) response = response.strip() raise Exception('HTTP Error: [%i] %s. Response: %s' % (resp.status, resp.reason, response[:256])) except tlslite.TLSLocalAlert as ex: response = None err('loadUrl failed: %s' % utils.hide_guid(traceback.format_exc())) errStr = str(ex) except tlslite.TLSFingerprintError as ex: response = None err('loadUrl failed: %s' % utils.hide_guid(traceback.format_exc())) errStr = str(ex) except Exception as ex: response = None errStr = str(ex) if not isinstance(errStr, unicode): errStr = errStr.decode(locale.getdefaultlocale()[1]).encode("utf-8") # log(errStr) tb = traceback.format_exc(1).split('\n') err('loadUrl failed: %s%s' % (utils.hide_guid(errStr), tb[1])) #finally: # if conn is not None: # conn.close() return (response, compressedSize, errStr)
def _loadUrl(u, timeout, body, content_type): # timeout in msec response = None compressedSize = None errStr = None conn = None try: #log(u) cls = httplib.HTTPSConnection if u.scheme.lower() == 'https' else httplib.HTTPConnection global _proxy #log(_proxy) if _proxy: conn = cls(_proxy.hostname, _proxy.port, timeout=timeout/1000) headers = {} if _proxy.username and _proxy.password: auth = '%s:%s' % (_proxy.username, _proxy.password) headers['Proxy-Authorization'] = 'Basic ' + base64.b64encode(auth) #log(headers) conn.set_tunnel(u.hostname, u.port, headers=headers) else: conn = cls(u.netloc, timeout=timeout/1000) global _USER_AGENT headers = { "User-Agent": _USER_AGENT, "Accept-Encoding": "gzip", "Content-Type": content_type} conn.request("POST" if body else "GET", u.path, body, headers) resp = conn.getresponse() # log(resp.status) response = resp.read() compressedSize = len(response) encoding = resp.getheader('content-encoding') if encoding is None: pass # leave response as is elif encoding == 'gzip': response = gzip.GzipFile(fileobj=StringIO.StringIO(response)).read() else: raise Exception('Encoding not supported: %s' % encoding) # log(response) if resp.status not in [200, 202, 204, 401]: # 200 OK, 202 Accepted, 204 No Content m = re.search(r'<body[^>]+?>\r?\n?(.+?)</body>', response, flags=re.S | re.I) if m: response = m.group(1) response = re.sub(r'<[^>]+>', '', response) response = re.sub(r'nginx/\d+\.\d+\.\d+', '', response) response = response.strip() raise Exception('HTTP Error: [%i] %s. Response: %s' % (resp.status, resp.reason, response[:256])) except Exception as ex: response = None errStr = str(ex) if not isinstance(errStr, unicode): errStr = errStr.decode(locale.getdefaultlocale()[1]).encode("utf-8") # log(errStr) tb = traceback.format_exc(1).split('\n') err('loadUrl failed: %s%s' % (utils.hide_guid(errStr), tb[1])) finally: if conn is not None: conn.close() return (response, compressedSize, errStr)
def _loadUrl(u, timeout, fingerprints, body): # timeout in msec response = None compressedSize = None errStr = None conn = None try: # log(u) if u.scheme.lower() == 'https': checker = tlslite.CheckerXfw( x509Fingerprint=fingerprints) if fingerprints else None conn = tlslite.HTTPTLSConnection(u.netloc, timeout=timeout / 1000, checker=checker) else: conn = httplib.HTTPConnection(u.netloc, timeout=timeout / 1000) global _USER_AGENT headers = { "User-Agent": _USER_AGENT, "Connection": "Keep-Alive", "Accept-Encoding": "gzip", "Content-Type": "text/plain; charset=utf-8" } conn.request("POST" if body else "GET", u.path, body, headers) resp = conn.getresponse() # log(resp.status) response = resp.read() compressedSize = len(response) encoding = resp.getheader('content-encoding') if encoding is None: pass # leave response as is elif encoding == 'gzip': response = gzip.GzipFile( fileobj=StringIO.StringIO(response)).read() else: raise Exception('Encoding not supported: %s' % encoding) # log(response) if resp.status not in [200, 202, 204, 401]: # 200 OK, 202 Accepted, 204 No Content m = re.search(r'<body[^>]+?>\r?\n?(.+?)</body>', response, flags=re.S | re.I) if m: response = m.group(1) response = re.sub(r'<[^>]+>', '', response) response = re.sub(r'nginx/\d+\.\d+\.\d+', '', response) response = response.strip() raise Exception('HTTP Error: [%i] %s. Response: %s' % (resp.status, resp.reason, response[:256])) except tlslite.TLSLocalAlert as ex: response = None err('loadUrl failed: %s' % utils.hide_guid(traceback.format_exc())) errStr = str(ex) except tlslite.TLSFingerprintError as ex: response = None err('loadUrl failed: %s' % utils.hide_guid(traceback.format_exc())) errStr = str(ex) except Exception as ex: response = None errStr = str(ex) if not isinstance(errStr, unicode): errStr = errStr.decode( locale.getdefaultlocale()[1]).encode("utf-8") # log(errStr) tb = traceback.format_exc(1).split('\n') err('loadUrl failed: %s%s' % (utils.hide_guid(errStr), tb[1])) # finally: # if conn is not None: # conn.close() return (response, compressedSize, errStr)