Пример #1
0
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())
Пример #2
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])
Пример #3
0
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())
Пример #4
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, 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])
Пример #5
0
    def _get_user(self):
        (value, isId) = self.req['args']
        orig_value = value
        reg = GAME_REGION
        if isId:
            value = str(int(value))
        else:
            if reg == "CT":
                suf = value[-3:]
                if suf in ('_RU', '_EU', '_NA', '_US', '_SG'):
                    reg = value[-2:]
                    value = value[:-3]
                    if reg == 'US':
                        reg = 'NA'
                else:
                    reg = "RU"
        cacheKey = "%s/%s" % ("ID" if isId else reg, value)
        data = None
        if cacheKey not in self.cacheUser:
            try:
                tdata = token.getXvmActiveTokenData()
                if tdata is None or 'token' not in tdata:
                    err('No valid token for XVM network services (key=%s)' % cacheKey)
                else:
                    tok = tdata['token'].encode('ascii')
                    if isId:
                        req = "user/%s/%s" % (tok, value)
                    else:
                        req = "nick/%s/%s/%s" % (tok, reg, value)
                    server = XVM.SERVERS[randint(0, len(XVM.SERVERS) - 1)]
                    (response, duration, errStr) = loadUrl(server, req)

                    # log(response)

                    if not response:
                        # err('Empty response or parsing error')
                        pass
                    else:
                        try:
                            data = None if response in ('', '[]') else simplejson.loads(response)[0]
                        except Exception:
                            err('  Bad answer: ' + response)

                        if data is not None:
                            self._fix_user(data, None if isId else orig_value)
                            if 'nm' in data and '_id' in data:
                                self.cacheUser[reg + "/" + data['nm']] = data
                                self.cacheUser["ID/" + str(data['_id'])] = data
                        elif response == '[]':
                            self.cacheUser[cacheKey] = {}

            except Exception:
                err(traceback.format_exc())

        with self.lock:
            self.resp = self.cacheUser.get(cacheKey, {})
Пример #6
0
    def _get_user(self):
        (value, isId) = self.req['args']
        orig_value = value
        reg = region
        if isId:
            value = str(int(value))
        else:
            if reg == "CT":
                suf = value[-3:]
                if suf in ('_RU', '_EU', '_NA', '_US', '_SG'):
                    reg = value[-2:]
                    value = value[:-3]
                    if reg == 'US':
                        reg = 'NA'
                else:
                    reg = "RU"
        cacheKey = "%s/%s" % ("ID" if isId else reg, value)
        data = None
        if cacheKey not in self.cacheUser:
            try:
                tdata = getXvmStatActiveTokenData()
                if tdata is None or not 'token' in tdata:
                    err('No valid token for XVM statistics (key=%s)' %
                        cacheKey)
                else:
                    tok = tdata['token'].encode('ascii')
                    if isId:
                        req = "user/%s/%s" % (tok, value)
                    else:
                        req = "nick/%s/%s/%s" % (tok, reg, value)
                    server = XVM_STAT_SERVERS[randint(
                        0,
                        len(XVM_STAT_SERVERS) - 1)]
                    (response, duration) = loadUrl(server, req)

                    if not response:
                        #err('Empty response or parsing error')
                        pass
                    else:
                        try:
                            data = None if response in (
                                '', '[]') else json.loads(response)[0]
                        except Exception, ex:
                            err('  Bad answer: ' + response)

                        if data is not None:
                            self._fix(data, None if isId else orig_value)
                            if 'nm' in data and '_id' in data:
                                self.cacheUser[reg + "/" + data['nm']] = data
                                self.cacheUser["ID/" + str(data['_id'])] = data
                        elif response == '[]':
                            self.cacheUser[cacheKey] = {}

            except Exception, ex:
                err('_get_user() exception: ' + traceback.format_exc())
Пример #7
0
def _load():
    res = None
    try:
        (response, duration) = loadUrl(__WN8_EXPECTED_DATA_URL)
        if not response:
            #err('Empty response or parsing error')
            pass
        else:
            try:
                data = None if response in ('', '[]') else json.loads(response)
                res = json.dumps(data)
            except Exception, ex:
                err('  Bad answer: ' + response)
                res = None
    except Exception, ex:
        err(traceback.format_exc())
Пример #8
0
def _checkVersion():
    playerId = getCurrentPlayerId()
    # fallback to the last player id if replay is running
    if playerId is None and isReplay():
        playerId = userprefs.get('tokens.lastPlayerId')
    if playerId is None:
        return

    global versionChecked
    versionChecked = True

    try:
        req = "checkVersion/%d" % playerId
        server = XVM.SERVERS[randint(0, len(XVM.SERVERS) - 1)]
        (response, duration, errStr) = loadUrl(server, req)

        # response =
        """ {
              "topClans":{"MGRD":{"rank":"747","cid":"156781"},...},
              "persistClans":{"WG-A":{"rank":"0","cid":"17996"},...},
              "info":{"RU": {"message":"www.modxvm.com","ver":"5.2.1-test2"},...}
            }"""

        global _clansInfo, _verInfo
        _clansInfo = None
        _verInfo = None
        if not response:
            # err('Empty response or parsing error')
            pass
        else:
            try:
                if response is not None:
                    response = response.strip()
                    if response not in ('', '[]'):
                        data = simplejson.loads(response)
                        if data is not None:
                            _clansInfo = _processClansInfo(data)
                            _verInfo = data.get('info', None)
                            global isOnline
                            isOnline = True
            except Exception, ex:
                err('  Bad answer: ' + response)
                err(traceback.format_exc())
                _clansInfo = None
                _verInfo = None
    except Exception, ex:
        err(traceback.format_exc())
Пример #9
0
def _load():
    res = {}
    try:
        (response, duration, errStr) = loadUrl(__WN8_EXPECTED_DATA_URL)
        if not response:
            # err('Empty response or parsing error')
            pass
        else:
            try:
                data = None if response in ("", "[]") else simplejson.loads(response)
                res = {}
                for x in data["data"]:
                    n = x["IDNum"]
                    del x["IDNum"]
                    res[str(n)] = x
            except Exception, ex:
                err("  Bad answer: " + response)
                res = {}
    except Exception, ex:
        err(traceback.format_exc())
Пример #10
0
def _load():
    res = {}
    try:
        (response, duration, errStr) = loadUrl(__WN8_EXPECTED_DATA_URL)
        if not response:
            # err('Empty response or parsing error')
            pass
        else:
            try:
                data = None if response in (
                    '', '[]') else simplejson.loads(response)
                res = {}
                for x in data['data']:
                    n = x['IDNum']
                    del x['IDNum']
                    res[str(n)] = x
            except Exception, ex:
                err('  Bad answer: ' + response)
                res = {}
    except Exception, ex:
        err(traceback.format_exc())
Пример #11
0
    def _load_stat(self, playerVehicleID, allowNetwork=True):
        requestList = []

        replay = isReplay()
        for vehId in self.players:
            pl = self.players[vehId]
            cacheKey = "%d=%d" % (pl.playerId, pl.vId)

            if cacheKey in self.cache:
                continue
            if str(pl.playerId) in self.playersSkip:
                continue

            #if pl.vId in [None, '', 'UNKNOWN']:
            #    requestList.append(str(pl.playerId))
            #else:
            requestList.append(
                "%d=%d%s" %
                (pl.playerId, pl.vId,
                 '=1' if not replay and pl.vehId == playerVehicleID else ''))

        if not requestList:
            return

        try:
            if allowNetwork:
                tdata = getXvmStatActiveTokenData()
                if tdata is None or not 'token' in tdata:
                    err('No valid token for XVM statistics (id=%s)' %
                        playerVehicleID)
                    return

                updateRequest = 'stat/%s/%s' % (tdata['token'].encode('ascii'),
                                                ','.join(requestList))

                if XVM_STAT_SERVERS is None or len(XVM_STAT_SERVERS) <= 0:
                    err('Cannot read statistics: no suitable server was found.'
                        )
                    return

                server = XVM_STAT_SERVERS[randint(0,
                                                  len(XVM_STAT_SERVERS) - 1)]
                (response, duration) = loadUrl(server, updateRequest)

                if not response:
                    #err('Empty response or parsing error')
                    return

                data = json.loads(response)
            else:
                players = []
                for vehId in self.players:
                    players.append(self._get_battle_stub(self.players[vehId]))
                data = {'players': players}

            if 'info' in data and region in data['info']:
                self.info = data['info'][region]

            if 'players' not in data:
                err('Stat request failed: ' + str(response))
                return

            for stat in data['players']:
                #debug(json.dumps(stat))
                self._fix(stat, None)
                #pprint(stat)
                if 'nm' not in stat or not stat['nm']:
                    continue
                if 'b' not in stat or stat['b'] <= 0:
                    continue
                cacheKey = "%d=%d" % (stat['_id'], stat.get('v', {}).get(
                    'id', 0))
                self.cache[cacheKey] = stat

        except Exception, ex:
            err('_load_stat() exception: ' + traceback.format_exc())
Пример #12
0
    def _load_stat(self, playerVehicleID):
        requestList = []

        replay = isReplay()
        all_cached = True
        for (vehId, pl) in self.players.iteritems():
            cacheKey = "%d=%d" % (pl.playerId, pl.vId)

            if cacheKey not in self.cacheBattle:
                all_cached = False

            requestList.append("%d=%d%s" % (pl.playerId, pl.vId,
                                            '=1' if not replay and pl.vehId == playerVehicleID else ''))

        if all_cached or not requestList:
            return

        try:
            tdata = token.getXvmActiveTokenData()
            if token.networkServicesSettings['statBattle']:
                if tdata is None or 'token' not in tdata:
                    err('No valid token for XVM network services (id=%s)' % playerVehicleID)
                    return

                cmd = 'rplstat' if isReplay() else 'stat'
                updateRequest = '%s/%s/%s' % (cmd, tdata['token'].encode('ascii'), ','.join(requestList))

                if XVM.SERVERS is None or len(XVM.SERVERS) <= 0:
                    err('Cannot read data: no suitable server was found.')
                    return

                server = XVM.SERVERS[randint(0, len(XVM.SERVERS) - 1)]
                (response, duration, errStr) = loadUrl(server, updateRequest)

                if not response:
                    # err('Empty response or parsing error')
                    return

                data = simplejson.loads(response)
                if 'players' not in data:
                    err('Stat request failed: ' + str(response))
                    return

            else:
                if isReplay():
                    log('XVM network services inactive (id=%s)' % playerVehicleID)
                players = []
                for (vehId, pl) in self.players.iteritems():
                    players.append(self._get_battle_stub(pl))
                data = {'players': players}

            for stat in data['players']:
                # debug(simplejson.dumps(stat))
                self._fix(stat)
                # pprint(stat)
                if 'nm' not in stat or not stat['nm']:
                    continue
                if 'b' not in stat or stat['b'] <= 0:
                    continue
                cacheKey = "%d=%d" % (stat['_id'], stat.get('v', {}).get('id', 0))
                self.cacheBattle[cacheKey] = stat

        except Exception:
            err(traceback.format_exc())
Пример #13
0
    def _load_stat(self, playerVehicleID, allowNetwork=True):
        requestList = []

        tdata = getXvmStatActiveTokenData()
        if tdata is None or not 'token' in tdata:
            err('No valid token for XVM statistics (id=%s)' % playerVehicleID)
            return

        isReplay = utils.is_replay()

        for vehId in self.players:
            pl = self.players[vehId]
            cacheKey = "%d=%d" % (pl.playerId, pl.vId)

            if cacheKey in self.cache:
                continue
            if str(pl.playerId) in self.playersSkip:
                continue

            #if pl.vId in [None, '', 'UNKNOWN']:
            #    requestList.append(str(pl.playerId))
            #else:
            requestList.append("%d=%d%s" % (pl.playerId, pl.vId,
                '=1' if not isReplay and pl.vehId == playerVehicleID else ''))

        if not requestList:
            return
        updateRequest = 'stat/%s/%s' % (tdata['token'].encode('ascii'), ','.join(requestList))

        if XVM_STAT_SERVERS is None or len(XVM_STAT_SERVERS) <= 0:
            err('Cannot read statistics: no suitable server was found.')
            return

        try:
            if allowNetwork:
                server = XVM_STAT_SERVERS[randint(0, len(XVM_STAT_SERVERS) - 1)]
                (response, duration) = loadUrl(server, updateRequest)

                if not response:
                    #err('Empty response or parsing error')
                    return

                data = json.loads(response)
            else:
                players = []
                for vehId in self.players:
                    players.append(self._get_battle_stub(self.players[vehId]))
                data = {'players':players}

            if 'info' in data and region in data['info']:
                self.info = data['info'][region]

            if 'players' not in data:
                err('Stat request failed: ' + str(response))
                return

            for stat in data['players']:
                #debug(json.dumps(stat))
                self._fix(stat, None)
                #pprint(stat)
                if 'nm' not in stat or not stat['nm']:
                    continue
                if 'b' not in stat or stat['b'] <= 0:
                    continue
                cacheKey = "%d=%d" % (stat['_id'], stat.get('v', {}).get('id', 0))
                self.cache[cacheKey] = stat

        except Exception, ex:
            err('_load_stat() exception: ' + traceback.format_exc())