def check_bankrupt(cls, uid, gid): benefit_times, bankrupt_ts = Context.Daily.get_daily_data( uid, gid, 'benefit_times', 'bankrupt_ts') benefit_times = Tool.to_int(benefit_times, 0) wait, which = None, None if bankrupt_ts: # 已经在破产状态, 未领取 which = benefit_times + 1 wait = int(bankrupt_ts) - Time.current_ts() if wait < 0: wait = 0 else: conf = Context.Configure.get_game_item_json(gid, 'benefit.config') if benefit_times < len(conf['reward']): reward = conf['reward'][benefit_times] bankrupt_ts = Time.current_ts() + reward['wait'] Context.Daily.set_daily_data(uid, gid, 'bankrupt_ts', bankrupt_ts) wait = reward['wait'] which = benefit_times + 1 mo = MsgPack(Message.FISH_MSG_BANKRUPT | Message.ID_NTF) mo.set_param('userId', uid) if wait is not None: mo.set_param('wait', wait) if which is not None: mo.set_param('which', which) # 可以领取哪一次 return mo
def query_chip_consume(self, gid, mi, request): room_types = (201, 202, 203) mini_games = (10002, 10003) fields = ['out.chip.attack'] for room_type in room_types: fields.append('out.chip.game.shot.bullet.%d' % room_type) for game in mini_games: fields.append('out.chip.game.%d' % game) start = mi.get_param('start') end = mi.get_param('end') start_day = Time.str_to_datetime(start, '%Y-%m-%d') end_day = Time.str_to_datetime(end, '%Y-%m-%d') mo = MsgPack(0) while start_day <= end_day: fmt = Time.datetime_to_str(start_day, '%Y-%m-%d') chips = Context.Stat.get_day_data(gid, fmt, *fields) attack = Tool.to_int(chips[0], 0) info = [] for chip in chips[1:]: if chip: info.append(int(chip)) else: info.append(0) info[2] += attack mo.set_param(fmt, info) start_day = Time.next_days(start_day) return mo
def query_pay_detail(self, gid, mi, request): conf = Context.Configure.get_game_item_json(gid, 'product.config') pids = [] for pid in conf.iterkeys(): pids.append('product_' + pid) start = mi.get_param('start') end = mi.get_param('end') start_day = Time.str_to_datetime(start, '%Y-%m-%d') end_day = Time.str_to_datetime(end, '%Y-%m-%d') mo = MsgPack(0) while start_day <= end_day: fmt = Time.datetime_to_str(start_day, '%Y-%m-%d') timess = Context.Stat.get_day_data(gid, fmt, *pids) kvs = {'product_100646': 0, 'product_100710': 0} for k, v in zip(pids, timess): pid = k.replace('product_', '') if pid in ('100646', '100647', '100648', '100649', '100650', '100651', '100652', '100653', '100654', '100655'): kvs['product_100646'] += Tool.to_int(v, 0) elif pid in ('100710', '100711', '100712', '100713', '100714', '100715', '100716'): kvs['product_100710'] += Tool.to_int(v, 0) else: kvs[k] = Tool.to_int(v, 0) mo.set_param(fmt, kvs) start_day = Time.next_days(start_day) return mo
def query_diamond_produce(self, gid, mi, request): start = mi.get_param('start') end = mi.get_param('end') start_day = Time.str_to_datetime(start, '%Y-%m-%d') end_day = Time.str_to_datetime(end, '%Y-%m-%d') mo = MsgPack(0) while start_day <= end_day: fmt = Time.datetime_to_str(start_day, '%Y-%m-%d') kvs = Context.Stat.get_day_data(gid, fmt) _kvs = {} total, task_total, fall_total = 0, 0, 0 for k, v in kvs.iteritems(): if k.startswith('in.diamond.'): if k.startswith('in.diamond.task.reward.'): task_total += int(v) elif k.startswith('in.diamond.fish.fall.'): fall_total += int(v) else: _kvs[k] = int(v) total += int(v) _kvs['in.diamond.task.reward'] = task_total _kvs['in.diamond.fish.fall'] = fall_total _kvs['in.diamond.buy.product'] = int(kvs.get('in.diamond.buy.product', 0)) _kvs['total'] = total mo.set_param(fmt, _kvs) start_day = Time.next_days(start_day) return mo
def on_create_user(cls, uid, gid): super(FishAccount, cls).on_create_user(uid, gid) # 发放一级礼包 conf = Context.Configure.get_game_item_json(gid, 'exp.level.reward') rewards_info = FishProps.issue_rewards(uid, gid, conf[0], 'exp.upgrade') rewards_info = FishProps.convert_reward(rewards_info) mo = MsgPack(Message.FISH_MSG_EXP_UPGRADE | Message.ID_NTF) mo.set_param('exp', 0) mo.set_param('lv', 1) mo.set_param('df', [1, [0, conf[1]]]) mo.update_param(rewards_info) Context.GData.send_to_connect(uid, mo) # new user carrying pipe_args = [] for k in ('chip', 'diamond', 'coupon'): if k in rewards_info: pipe_args.append('login.carrying.volume.%s' % k) pipe_args.append(rewards_info[k]) if 'chip' in rewards_info: pipe_args.append('carrying.volume.chip') pipe_args.append(rewards_info['chip']) if pipe_args: Context.Stat.mincr_daily_data(gid, *pipe_args)
def query_chip_produce(self, gid, mi, request): start = mi.get_param('start') end = mi.get_param('end') start_day = Time.str_to_datetime(start, '%Y-%m-%d') end_day = Time.str_to_datetime(end, '%Y-%m-%d') mo = MsgPack(0) while start_day <= end_day: fmt = Time.datetime_to_str(start_day, '%Y-%m-%d') kvs = Context.Stat.get_day_data(gid, fmt) task_total, catch_total = 0, 0 _kvs = {} for k, v in kvs.iteritems(): if k.startswith('in.chip.'): if k.startswith('in.chip.task.reward.'): task_total += int(v) elif k.startswith('in.chip.catch.fish.'): catch_total += int(v) else: _kvs[k] = int(v) _kvs['in.chip.task.reward'] = task_total _kvs['in.chip.catch.fish'] = catch_total _kvs['in.chip.buy.product'] = int(kvs.get('in.chip.buy.product', 0)) mo.set_param(fmt, _kvs) start_day = Time.next_days(start_day) return mo
def get_ranks(self, uid, gid, mi): rank_name = mi.get_param('rank') if not rank_name: rank_name = ['chip', 'exp'] elif isinstance(rank_name, (str, unicode)): rank_name = [rank_name] start = mi.get_param('start', 0) end = mi.get_param('end', 49) if start < 0 or end < start: return if end - start > 49: end = start + 49 mo = MsgPack(Message.MSG_SYS_RANK_LIST | Message.ID_ACK) rank_list, mine = {}, {} if 'chip' in rank_name: _, rank_list['chip'] = self.get_chip_rank_list( uid, gid, start, end) if 'exp' in rank_name: _, rank_list['exp'] = self.get_exp_rank_list(uid, gid, start, end) mo.update_param(rank_list) if 'chip' in rank_list or 'exp' in rank_list: _info = self.__get_user_info(uid, gid) mine.update(_info) if mine: mo.set_param('mine', mine) return mo
def query_chip_pump(self, gid, mi, request): room_types = (201, 202, 203) fields = [] for room_type in room_types: fields.append('out.chip.pump.%d' % room_type) fields.append('out.chip.buff.pump.%d' % room_type) fields.append('out.chip.red.pump.%d' % room_type) start = mi.get_param('start') end = mi.get_param('end') start_day = Time.str_to_datetime(start, '%Y-%m-%d') end_day = Time.str_to_datetime(end, '%Y-%m-%d') mo = MsgPack(0) while start_day <= end_day: fmt = Time.datetime_to_str(start_day, '%Y-%m-%d') chips = Context.Stat.get_day_data(gid, fmt, *fields) info = [] for i in range(0, len(chips), 3): total = 0 for j in range(3): if chips[i + j]: total += int(chips[i + j]) info.append(total) mo.set_param(fmt, info) start_day = Time.next_days(start_day) return mo
def on_join_table(self, gid, msg): ack = MsgPack(Message.MSG_SYS_JOIN_TABLE | Message.ID_ACK) tid = msg.get_param('tableId') self._info('player req to join table', tid) self.offline = False if self.tid > 0 and self.tid != tid: self.offline = True return ack.set_error(Enum.join_table_failed_multi) registry = Context.get_module(gid, 'registry') table = registry.create_table(gid, tid) if not table: self.offline = True return ack.set_error(Enum.join_table_failed_id) result = table.join_table(self.uid) if result != 0: self.offline = True return ack.set_error(result) self.table = table self.online_ts = Time.current_ts() sid = msg.get_param('seatId') if sid is not None: return self.on_sit_down(msg) return result
def deliverOrder(self, mi, request): gid = mi.get_param('gameId') order_list = mi.get_param('orders') if not Entity.logined(request): return MsgPack.Error(0, Const.E_NOT_LOGIN, Const.ES_NOT_LOGIN) uid = request.getSession().userId orders = [] for orderId in order_list: orderInfo = self.getOrderInfo(orderId) if not orderInfo: continue userId = int(orderInfo['userId']) gameId = int(orderInfo['gameId']) state = int(orderInfo['state']) if userId != uid: Context.Log.warn('userId not match', userId, uid, orderId) continue if gameId != gid: Context.Log.warn('gameId not match', gameId, gid, orderId) continue if state == self.state_create: create_ts = Time.str_to_timestamp(orderInfo['createTime'], '%Y-%m-%d %X.%f') now_ts = Time.current_ts() if now_ts - create_ts > 3600: state = self.state_timeout orders.append({'id': orderId, 'state': state}) return MsgPack(0, {'orders': orders})
def query_diamond_consume(self, gid, mi, request): start = mi.get_param('start') end = mi.get_param('end') start_day = Time.str_to_datetime(start, '%Y-%m-%d') end_day = Time.str_to_datetime(end, '%Y-%m-%d') mo = MsgPack(0) while start_day <= end_day: fmt = Time.datetime_to_str(start_day, '%Y-%m-%d') kvs = Context.Stat.get_day_data(gid, fmt) _kvs, total = {}, 0 for k, v in kvs.iteritems(): if k.startswith('out.diamond.'): if k.startswith('out.diamond.inner.buy.'): k = 'out.diamond.buy.' + k[-3:] elif k.startswith('out.diamond.table.buy.'): k = 'out.diamond.buy.' + k[-3:] if k in _kvs: _kvs[k] += int(v) else: _kvs[k] = int(v) total += int(v) _kvs['total'] = total mo.set_param(fmt, _kvs) start_day = Time.next_days(start_day) return mo
def gm_push_led(self, gid, mi, request): msg = mi.get_param('msg') if not msg: # 清除led Context.RedisCache.delete('game.%d.led.list' % gid) else: led = Context.json_dumps({'led': msg, 'ts': Time.current_ts()}) Context.RedisCache.list_lpush('game.%d.led.list' % gid, led) return MsgPack(0)
def onGameInfo(self, uid, gid, mi): gid = mi.get_param('gameId') mo = MsgPack(Message.MSG_SYS_GAME_INFO | Message.ID_ACK) account = Context.get_module(gid, 'account', Account) is_new, data = account.get_game_info(uid, gid) if not data: mo.set_error(-1, 'no game info') else: mo.update_param(data) if is_new: mo.set_param('new', 1) info = Context.RedisCache.hash_mget('global.notice', 'led', 'start', 'end') led = info[0] if led: now_ts = Time.current_ts() start = int(info[1]) end = int(info[2]) if start < now_ts < end: mo.set_param('global_notice', { 'list': [led], 'end': end, 'now_ts': now_ts }) Context.GData.send_to_connect(uid, mo) if is_new: account.on_create_user(uid, gid) if account.auto_issue_benefit: benefit_config = Context.Configure.get_game_item_json( gid, 'benefit.config') if benefit_config and benefit_config['limit'] > data['chip']: benefit = Context.Daily.issue_benefit(uid, gid) mo = MsgPack(Message.MSG_SYS_BENEFIT | Message.ID_NTF) if not benefit: benefit = { 'which': 0, 'total': 0, 'reward': 0, 'chip': data['chip'], } mo.update_param(benefit) Context.GData.send_to_connect(uid, mo)
def gm_reward_chip(self, gid, mi, request): uid = mi.get_param('userId') if not Context.UserAttr.check_exist(uid, gid): return MsgPack.Error(0, 1, 'not exist') chip = mi.get_param('chip') real, final = Context.UserAttr.incr_chip(uid, gid, chip, 'gm.reward') if real != chip: MsgPack.Error(0, 1, 'not enough') return MsgPack(0, {'chip': final, 'delta': real})
def gm_exchange_phone(self, gid, mi, request): uid = mi.get_param('userId') seq = mi.get_param('seq') state = Context.RedisCluster.hash_get_int(uid, 'history:%d:%d' % (gid, uid), seq) if state is None: return MsgPack.Error(0, 1, 'error seq') if state == 1: return MsgPack.Error(0, 2, 'already exchange') Context.RedisCluster.hash_set(uid, 'history:%d:%d' % (gid, uid), seq, 1) return MsgPack(0)
def on_room_list(self, uid, gid, mi): room_config = Context.Configure.get_room_config(gid) if not room_config: Context.Log.error(uid, 'req room list, but no config fetch') return False conf = Context.copy_json_obj(room_config) mo = MsgPack(Message.MSG_SYS_ROOM_LIST | Message.ID_ACK) mo.set_param('room_list', conf) return Context.GData.send_to_connect(uid, mo)
def gm_reward_diamond(self, gid, mi, request): uid = mi.get_param('userId') if not Context.UserAttr.check_exist(uid, gid): return MsgPack.Error(0, 1, 'not exist') diamond = mi.get_param('diamond') real, final = Context.UserAttr.incr_diamond(uid, gid, diamond, 'gm.reward') if real != diamond: MsgPack.Error(0, 1, 'not enough') return MsgPack(0, {'diamond': final, 'delta': real})
def disable_user(self, gid, mi, request): uid = mi.get_param('userId') if not Context.UserAttr.check_exist(uid, gid): return MsgPack.Error(0, 1, 'not exist') disable = mi.get_param('disable') if disable: Context.RedisMix.set_add('game.%d.disable.user' % gid, uid) else: Context.RedisMix.set_rem('game.%d.disable.user' % gid, uid) return MsgPack(0)
def registerByMobile(self, mi, request): gid = mi.get_param('gameId') mobile = mi.get_param('mobile', '') passwd = mi.get_param('passwd', '') deviceId = mi.get_param('deviceId', '') nick = mi.get_param('nick', '') verifyCode = mi.get_param('verifyCode', '') platform = mi.get_param('platform', 'android') channel = mi.get_param('channel', 'jiyu') if not Entity.checkMobile(mobile): return MsgPack.Error(0, 1, 'param mobile invalid') if not Entity.checkPassword(passwd): return MsgPack.Error(0, 2, 'param passwd invalid') if not Entity.checkNick(nick): return MsgPack.Error(0, 3, 'param nick invalid') # 先查表,判断用户存不存在 idType = Const.IDTYPE_MOBILE userId = Account.getUserIDByUserName(mobile, idType) if userId: return MsgPack.Error(0, 4, 'mobile exist') if not Mobile.checkVerifyCode(gid, mobile, verifyCode): return MsgPack.Error(0, 5, 'verifycode not right') # nick 唯一 nick_unique_key = 'game.%d.unique.nick' % gid if not Context.RedisMix.hash_setnx(nick_unique_key, nick, 0): return MsgPack.Error(0, 6, 'nick not unique') # 插入用户数据 strMd5Pass = Entity.encodePassword(mobile, passwd) dictInfo = { 'idType': idType, 'deviceId': deviceId, 'userName': mobile, 'nick': nick, 'createIp': request.getClientIP(), 'token': strMd5Pass, 'guest': 0, 'channel': channel, 'platform': platform } userId = Account.createUser(dictInfo) if not userId: Context.RedisMix.hash_del(nick_unique_key, nick) return MsgPack.Error(0, Const.E_BAD_REDIS, Const.ES_BAD_REDIS) Context.RedisMix.hash_set(nick_unique_key, nick, userId) key, field = 'game.%d.info.hash' % gid, '%s.new.user.count' % channel Context.RedisMix.hash_incrby(key, field, 1) Context.Stat.incr_daily_data(gid, field, 1) return MsgPack(0)
def on_bind_game(self, cmd, raw): mi = MsgPack.unpack(cmd, raw) gid = mi.get_param('gameId') if gid > 0: room = mi.get_param('room') self.connection.bind_game(gid, room) mo = MsgPack(Message.MSG_SYS_BIND_GAME | Message.ID_ACK) mo.set_param('gameId', gid) Context.GData.send_to_client(self.connection.userId, mo, self.connection) return True
def setTimeout(self, second, param, *args, **kwargs): self.type = self.TIMER_ONCE self.second = second msg = MsgPack(Message.MSG_INNER_TIMER, param) uid = msg.get_param('userId') gid = msg.get_param('gameId') msg = MsgLine(msg.pack(), gid, target=uid).pack() task = self.tasklet(Message.to_inner(Message.MSG_INNER_TIMER), msg, None).run self.timer = TaskManager.call_later(self.__timeout, second, msg, task, *args, **kwargs) return True
def gm_account_block(self, gid, mi, request): uid = mi.get_param('userId') odds = mi.get_param('odds') if odds is None: Context.Data.del_game_attrs(uid, gid, 'block') else: if not Context.UserAttr.check_exist(uid, gid): return MsgPack.Error(0, 1, 'not exist') if odds <= 0 or odds > 1: return MsgPack.Error(0, 2, 'odds limit (0, 1]') Context.Data.set_game_attr(uid, gid, 'block', odds) return MsgPack(0)
def upgradeByMobile(self, mi, request): gid = mi.get_param('gameId') nick = mi.get_param('nick', '') mobile = mi.get_param('mobile', '') passwd = mi.get_param('passwd', '') verifyCode = mi.get_param('verifyCode', '') if not Entity.logined(request): return MsgPack.Error(0, Const.E_NOT_LOGIN, Const.ES_NOT_LOGIN) if not Entity.checkMobile(mobile): return MsgPack.Error(0, 1, 'mobile invalid') if not Entity.checkPassword(passwd): return MsgPack.Error(0, 2, 'password invalid') if not Entity.checkNick(nick): return MsgPack.Error(0, 6, 'nick invalid') userId = request.getSession().userId # 先判断是不是游客 userInfo = Account.getUserInfo(userId) if int(userInfo['idType']) != Const.IDTYPE_GUEST: return MsgPack.Error(0, 3, 'not guest') # 先查表,判断用户存不存在 if Account.getUserIDByUserName(mobile, Const.IDTYPE_MOBILE): return MsgPack.Error(0, 4, 'mobile exist') if not Mobile.checkVerifyCode(gid, mobile, verifyCode): return MsgPack.Error(0, 5, 'verifycode not right') # nick 唯一 if not Context.RedisMix.hash_setnx('game.%d.unique.nick' % gid, nick, 0): return MsgPack.Error(0, 7, 'nick not unique') if not Account.createUserName(Const.IDTYPE_MOBILE, mobile, userId): Context.RedisMix.hash_del('game.%d.unique.nick' % gid, nick) return MsgPack.Error(0, Const.E_BAD_REDIS, Const.ES_BAD_REDIS) if not Account.deleteUserName(userInfo['userName'], Const.IDTYPE_GUEST): Context.Log.error(userId, 'DeleteUserName failed,userName:'******'userName']) Context.RedisMix.hash_set('game.%d.unique.nick' % gid, nick, userId) Account.updateUserInfo(userId, userName=mobile, nick=nick, idType=Const.IDTYPE_MOBILE, token=Entity.encodePassword(mobile, passwd)) return MsgPack(0)
def process_login(self, mi): uid = mi.get_param('userId') gid = mi.get_param('gameId') session = mi.get_param('session') result, desc = Account.check_forbidden(uid, gid, session) if result: mo = MsgPack(Message.MSG_SYS_USER_INFO | Message.ID_ACK) mo.set_error(result, desc) return Context.GData.send_to_client(uid, mo, self.connection) if uid in Context.GData.map_client_connect: # 多点登陆 # 清除原来的client connection = Context.GData.map_client_connect[uid] mo = MsgPack(Message.MSG_SYS_MULTIPLE_LOGIN | Message.ID_NTF) Context.Log.info('multi login', uid) Context.GData.send_to_client(connection.userId, mo, connection) connection.terminate_connection() Context.GData.map_client_connect[uid] = self.connection self.connection.login(uid, gid) return True
def terminate_connection(self): if self.userId > 0: if self.userId in Context.GData.map_client_connect: del Context.GData.map_client_connect[self.userId] msg = MsgPack(Message.MSG_INNER_BROKEN) msg.set_param('userId', self.userId) if self.gameId > 0: msg.set_param('gameId', self.gameId) tasklet = self.makeTasklet(Message.MSG_INNER_BROKEN, msg, self) TaskManager.run_task(tasklet) self.logout() self.transport.loseConnection()
def getLoginInfo(cls, request, cmd, uid, gid, param, userInfo, freshAccessToken, openid=None, open_token=None): session = Algorithm.md5_encode(Time.asctime() + request.getClientIP() + userInfo['userName']) Account.setUserToken(uid, gid, session) conn_server = Context.json_loads( Context.RedisCache.get('connect.server')) internet = conn_server[uid % len(conn_server)] dictInfo = { "session": session, "userId": uid, "sex": int(userInfo['sex']), "nick": userInfo['nick'], "avatar": userInfo['avatar'], "host": internet["domain"], "port": internet["port"], } if openid: dictInfo['openid'] = openid if open_token: dictInfo['open_token'] = open_token if freshAccessToken: data = '{"uid":%d,"ct":%d}' % (uid, Time.current_ts()) accessToken = Entity.encrypt(data) Account.updateUserInfo(uid, accessToken=accessToken) dictInfo['accessToken'] = accessToken kvs = { 'session_platform': param['platform'] or 'android', 'session_channel': param['channel'] or 'jiyu', 'session_ver': param['releaseVer'] or '1.0.1' } Context.Data.set_game_attrs_dict(uid, gid, kvs) Context.Log.report('user.login:', [uid, gid, kvs]) # 登录成功设置session值 session = request.getSession() session.setLogined(uid) return MsgPack(cmd, dictInfo)
def on_sit_down(self, msg): sid = msg.get_param('seatId') self._info('player req to sit table %d at %d' % (self.tid, sid)) ack = MsgPack(Message.MSG_SYS_SIT_DOWN | Message.ID_ACK) table = Context.GData.online_table.get(self.tid) if not table: self._error('not exists the table', self.tid) return ack.set_error(Enum.sit_down_failed_id) result = table.sit_down(self.uid, sid) if result != 0: return ack.set_error(result) return result
def on_leave_table(self, msg): self._info('player req to leave table', self.tid) ack = MsgPack(Message.MSG_SYS_LEAVE_TABLE | Message.ID_ACK) table = Context.GData.online_table.get(self.tid) if not table: self._error('not exists the table', self.tid) return ack.set_error(Enum.leave_table_failed_id) result = table.leave_table(self.uid) if result != 0: return ack.set_error(result) return result
def gm_reward_card(self, gid, mi, request): uid = mi.get_param('userId') days = mi.get_param('days') if days <= 0: return MsgPack.Error(0, 1, 'error days') if not Context.UserAttr.check_exist(uid, gid): return MsgPack.Error(0, 2, 'not exist') state, days = FishProps.incr_vip(uid, gid, days, 'gm.reward') mo = MsgPack(0) mo.set_param('days', days) return mo
def freeze_user(self, gid, mi, request): uid = mi.get_param('userId') if not Context.UserAttr.check_exist(uid, gid): return MsgPack.Error(0, 1, 'not exist') days = mi.get_param('days') mo = MsgPack(0) if days is None: Context.RedisMix.hash_del('game.%d.freeze.user' % gid, uid) else: end_ts = Time.today_start_ts() + days * 3600 * 24 Context.RedisMix.hash_set('game.%d.freeze.user' % gid, uid, end_ts) mo.set_param('end_ts', end_ts) return mo