def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope, clientIds): button = runhttp.getParamStr('button', None) button = strutil.loads(button, ignoreException=True) data = None mo = MsgPack() if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0: # 发送私人消息 # 必须参数 # 1)msg - 消息 # 2)toUid - 接收消息的userId # 3)gameId data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button) elif mtype == 1 and len(msg) > 0 and gameId >= 0: # 发送站内消息到全体用户 # 必选参数 # msg - 消息 # gameId data = pkmessage.sendGlobal(gameId, msg, button) elif mtype == 2 and gameId > 0 and len(msg) > 0: # 发送LED # TODO 当前Game服务为4,5,6号 , 每个服务都发送 mo.setCmd('send_led') mo.setParam('msg', msg) mo.setParam('gameId', gameId) mo.setParam('ismgr', 1) router.sendToAll(mo, gdata.SRV_TYPE_UTIL) data = True elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0: # 封装popwnd # 必选参数 # gameId # toUid 接收弹窗的userId # msg 弹窗消息内容 task = TodoTaskShowInfo(msg, True) mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task) # 将消息发送给此人 router.sendToUser(mo, toUid) data = True elif mtype == 4 and gameId > 0 and len(msg) > 0 and len(scope) > 0: mo.setCmd('send_led') mo.setParam('msg', msg) ftlog.info('send_led new msg=', msg) mo.setParam('gameId', gameId) ftlog.info('send_led new gameId=', gameId) mo.setParam('ismgr', ismgr) ftlog.info('send_led new ismgr=', ismgr) mo.setParam('scope', scope) ftlog.info('send_led new scope=', scope) mo.setParam('clientIds', clientIds) ftlog.info('send_led new clientIds=', clientIds) router.sendToAll(mo, gdata.SRV_TYPE_UTIL) data = True if data == None: mo.setError(1, 'params error') else: mo.setResult('ok', 'true') return mo
def doExchange(self, gameId, userId): try: msg = runcmd.getMsgPack() couponId = msg.getParam('id') phone = msg.getParam('phone') if not phone: phone = msg.getParam('phoneNumber') if not phone: pp = msg.getParam('params', {}) if isinstance(pp, dict): phone = pp.get('phoneNumber') if not phone: if ftlog.is_debug(): ftlog.debug('ExchangeHandler.doExchange gameId=', gameId, 'userId=', userId, 'couponId=', couponId, 'phone=', phone) raise TYBizException(-1, 'Please input phone number') _trueDelta, final = self._getCouponService().exchangeCouponItem( userId, couponId, phone=phone) mo = MsgPack() mo.setCmd('exchange') mo.setResult('action', 'exchange') mo.setResult('id', couponId) mo.setResult('info', '兑换请求处理成功') mo.setResult('quan_left', final) router.sendToUser(mo, userId) except TYBizException, e: mo = MsgPack() mo.setCmd('exchange') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId)
def _doTcpPortTuyou(): mo = MsgPack() mo.setCmd('hellotcp') userId = runhttp.getParamInt('userId') nicaiCode = runhttp.getParamStr('nicaiCode', '') clientId = runhttp.getParamStr('clientId', '') if not nicaiCode: mo.setError(3, 'nicai error !') return mo if userId < 1: mo.setError(3, 'userId error !') return mo ftlog.debug('tcpport->userId=', userId, 'nicaiCode=', nicaiCode) HelloTuyou.getNiCaiCode(mo, nicaiCode) ip, port = getGaoFangIp2(userId, clientId) if not ip: ipports = gdata.getUserConnIpPortList() address = ipports[userId % len(ipports)] ip, port = getGaoFangIp(clientId, address[0], address[1]) ftlog.info('doTcpPortTuyou->', userId, ip, port) mo.setResult('tcpsrv', {'ip': ip, 'port': port}) return mo
def doConsumDelivery(self, appId, userId, orderId, prodId, prodCount, platformOrder): ftlog.info('doConsumDelivery->', appId, userId, orderId, prodId, prodCount, platformOrder) appKey = hallconf.getAppKeyInfo(appId).get('key', '') if not runhttp.checkHttpParamCode(appKey): mo = MsgPack() mo.setCmd('prod_delivery') mo.setError(1, '校验失败') ftlog.info('doConsumDelivery->', appId, userId, orderId, prodId, prodCount, platformOrder, 'result=code verify error') return mo userdata.clearUserCache(userId) mo = MsgPack() mo.setCmd('prod_delivery') mo.setParam('userId', userId) mo.setParam('orderId', orderId) mo.setParam('prodCount', prodCount) mo.setParam('prodId', prodId) mo.setParam('appId', appId) mo.setParam('orderPlatformId', platformOrder) mo.setParam('ok', '1') isSub = runhttp.getParamInt('is_monthly', 0) if isSub: mo.setParam('isSub', isSub) chargeType, chargeMap, consumeMap = self.getChargeInfos() mo.setParam('consumeMap', consumeMap) mo.setParam('chargeMap', chargeMap) mo.setParam('chargeType', chargeType) ret = router.queryUtilServer(mo, userId) ftlog.info('doConsumDelivery->', appId, userId, orderId, prodId, prodCount, platformOrder, 'result=', ret) if isinstance(ret, (str, unicode)) and ret.find('error') < 0: return 'success' return 'error'
def doDeliveryProduct(self, uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error): ftlog.info('doDeliveryProduct->', uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error) userdata.clearUserCache(uid) mo = MsgPack() mo.setCmd('prod_delivery') mo.setParam('userId', uid) mo.setParam('orderId', orderId) mo.setParam('prodId', prodId) mo.setParam('orderPrice', orderPrice) mo.setParam('orderPlatformId', platformOrder) if isError == 'true': mo.setResult('ok', '0') mo.setResult('info', error) mo.setError(1, error) router.sendToUser(mo, uid) return 'success' else: mo.setParam('ok', '1') isSub = runhttp.getParamInt('is_monthly', 0) if isSub: mo.setParam('isSub', isSub) ret = router.queryUtilServer(mo, uid) ftlog.info('doDeliveryProduct->', uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error, 'result=', ret) if isinstance(ret, (str, unicode)) and ret.find('error') < 0: return 'success' return 'error'
def _doTcpPortTuyou(): mo = MsgPack() mo.setCmd('hellotcp') userId = runhttp.getParamInt('userId') nicaiCode = runhttp.getParamStr('nicaiCode', '') clientId = runhttp.getParamStr('clientId', '') if not nicaiCode: mo.setError(3, 'nicai error !') return mo if userId < 1: mo.setError(3, 'userId error !') return mo ftlog.debug('tcpport->userId=', userId, 'nicaiCode=', nicaiCode) HelloTuyou.getNiCaiCode(mo, nicaiCode) ip, port, wsport = getGaoFangIp2(userId, clientId) if not ip: ipports = gdata.getUserConnIpPortList() address = ipports[userId % len(ipports)] ip, port = getGaoFangIp(clientId, address[0], address[1]) if len(address) > 2 : wsport = address[2] ftlog.info('doTcpPortTuyou->', userId, ip, port) mo.setResult('tcpsrv', {'ip': ip, 'port': port, 'wsport' : wsport}) return mo
def doItemUseOld(self, gameId, userId, itemId, clientId): try: # 老版本只认30这个itemId if itemId == 30: itemId = 2003 itemId = ItemHelper.translateItemId(gameId, 9999, itemId) userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() item = self._ensureItemExistsOld(userBag, itemId) actionName = ItemHelper.translateUseActionName(item) if actionName: actionResult = userBag.doAction(gameId, item, actionName) router.sendToUser( ItemHelper.makeDoActionResponse(gameId, userId, actionResult), userId) router.sendToUser( ItemHelper.makeItemListResponse(gameId, userId), userId) else: mo = MsgPack() mo.setCmd('bag') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('itemId', itemId) mo.setError(-1, '该道具不能使用') router.sendToUser(mo, userId) except TYBizException, e: self.handleException(itemId, gameId, userId, clientId, e)
def doCheckinMonth(self, gameId, userId, clientId): try: mo = MsgPack() mo.setCmd('month_checkin') status = monthcheckin.checkin(userId, gameId, clientId) if not status: mo.setResult('userId', userId) ftlog.info('maybe is script userId =', userId) mo.setResult('tip', 'maybe is script') router.sendToUser(mo, userId) return mo.setResult( 'checkinDateList', [d.strftime('%Y%m%d') for d in status.checkinDateList]) mo.setResult('supplementCheckinDateList', [ d.strftime('%Y%m%d') for d in status.supplementCheckinDateList ]) mo.setResult('rewardDaysList', status.rewardDaysList) mo.setResult('descSucess', '恭喜你获得500金币+1幸运卡') mo.setResult( 'supCheckinCount', monthcheckin.getSupplementCheckinCardCount(userId, gameId)) daysRewards = [] for _days, rewardContent in enumerate(monthcheckin.getConf().get( 'daysRewards', [])): reward = rewardContent.get('reward') monthRange = monthcheckin.getMonthRange() if rewardContent.get('days') < monthRange: monthRange = rewardContent.get('days') daysRewards.append({ 'days': monthRange, 'desc': reward.get('desc'), 'picUrl': reward.get('picUrl'), 'state': self.calcDaysRewardState(status, monthRange) }) ftlog.debug('doCheckinMonth daysRewards monthRange =', monthRange) mo.setResult('daysRewards', daysRewards) mo.setResult('action', 'checkin') ftlog.debug('doCheckinMonth userId =', userId, 'gameId =', gameId, 'clientId =', clientId, 'checkinDateList =', [d.strftime('%Y%m%d') for d in status.checkinDateList], 'supplementCheckinDateList =', [ d.strftime('%Y%m%d') for d in status.supplementCheckinDateList ]) router.sendToUser(mo, userId) datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'checkin') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.warn('MonthCheckinException', userId, e.errorCode, e.message)
def _onEnterRoomFailed(cls, msg, checkResult, userId, gameId, clientId, roomId=0): '''进入房间失败回调函数''' ftlog.warn("|userId, reason, roomId:", userId, checkResult, roomId, caller=cls) # 调用最小房间金币不够充值提醒的todotask if not roomId: roomId = msg.getParam('candidateRoomId', 0) if checkResult == TYRoom.ENTER_ROOM_REASON_LESS_MIN or checkResult == 104: from hall.entity import hallproductselector product, _ = hallproductselector.selectLessbuyProduct( gameId, userId, clientId, roomId) if product: from hall.entity.todotask import TodoTaskOrderShow todotask = TodoTaskOrderShow.makeByProduct( "金币不够啦,买一个超值礼包吧!", "", product) if todotask: TodoTaskHelper.sendTodoTask(gameId, userId, todotask) mo = MsgPack() mo.setCmd('quick_start') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setError(checkResult, '进入房间失败,请稍后重试') router.sendToUser(mo, userId)
def doQueryDailyFreeGive(self, gameId, userId, shareId, clientId): try: mo = MsgPack() mo.setCmd('daily_free_give') mo.setResult('action', 'query') mo.setResult('dailyFreeGive', daily_free_give.queryDailyFreeGive(userId, gameId)) mo.setResult( 'todayCheckIn', sevendayscheckin.loadStatus(userId, gameId).isTodayCheckined()) share = hallshare.findShare(shareId) if share: shareInfo = hallshare.getShareStatus( userId, share, pktimestamp.getCurrentTimestamp()) mo.setResult('shareRewardCount', shareInfo[1]) else: mo.setResult('shareRewardCount', 0) router.sendToUser(mo, userId) #统计 bireport.reportGameEvent('SZMJ_DAILY_FREE_GIVE_QUERY', userId, gameId, 0, 0, 0, 0, 0, 0, [], clientId) except Exception as e: mo = MsgPack() mo.setCmd('daily_free_give') mo.setResult('action', 'query') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId)
def doRecieveDailyFreeGive(self, gameId, userId, clientId): try: mo = MsgPack() mo.setCmd('daily_free_give') mo.setResult('action', 'recieve') ret = daily_free_give.receiveDailyFreeGive(userId, gameId) if not ret: mo.setResult('ok', 0) ftlog.info('maybe is script userId =', userId) mo.setResult('tip', '领取失败') router.sendToUser(mo, userId) return mo.setResult('deltaChip', ret[1]) mo.setResult('finalChip', ret[2]) mo.setResult('freeGiveCountLeft', ret[3]) mo.setResult('ok', 1) router.sendToUser(mo, userId) #统计 bireport.reportGameEvent('SZMJ_DAILY_FREE_GIVE_RECIEVE', userId, gameId, 0, 0, 0, 0, 0, 0, [], clientId) except Exception as e: mo = MsgPack() mo.setCmd('daily_free_give') mo.setResult('action', 'recieve') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId)
def doExchange(self, gameId, userId): try: msg = runcmd.getMsgPack() couponId = msg.getParam('id') phone = msg.getParam('phone') if not phone: phone = msg.getParam('phoneNumber') if not phone: pp = msg.getParam('params', {}) if isinstance(pp, dict): phone = pp.get('phoneNumber') if not phone: if ftlog.is_debug(): ftlog.debug('ExchangeHandler.doExchange gameId=', gameId, 'userId=', userId, 'couponId=', couponId, 'phone=', phone) raise TYBizException(-1, 'Please input phone number') _trueDelta, final = self._getCouponService().exchangeCouponItem(userId, couponId, phone=phone) mo = MsgPack() mo.setCmd('exchange') mo.setResult('action', 'exchange') mo.setResult('id', couponId) mo.setResult('info', '兑换请求处理成功') mo.setResult('quan_left', final) router.sendToUser(mo, userId) except TYBizException, e: mo = MsgPack() mo.setCmd('exchange') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId)
def doGiveup(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) if not self.match.giveup(userId): mo = MsgPack() mo.setCmd('room') mo.setError(-1, '不能退出比赛') router.sendToUser(mo, userId)
def _do_room__giveup(self, msg): if ftlog.is_debug(): ftlog.debug('DizhuErdayiMatchCtrlRoom._do_room__giveup', msg) userId = msg.getParam('userId') mo = MsgPack() mo.setCmd('room') mo.setError(-1, '不能退出比赛') router.sendToUser(mo, userId)
def doActivityBetguessSetResultGdss(self): ec, result = self.checkCode() if ec != 0: mo = MsgPack() mo.setError(ec, result) return mo return self.doActivityBetguessSetResult()
def doGiveup(self, userId): if self._logger.isDebug(): self._logger.debug('TYErdayiMatchRoom.doGiveup', 'userId=', userId) mo = MsgPack() mo.setCmd('room') mo.setError(-1, '不能退出比赛') router.sendToUser(mo, userId)
def doGetDaysRewardMonth(self, gameId, userId, clientId): msg = runcmd.getMsgPack() days = msg.getParam('days') try: mo = MsgPack() MonthCheckinStatus = monthcheckin.getDaysReward( userId, days, gameId) mo.setCmd('month_checkin') if not MonthCheckinStatus: mo.setResult('userId', userId) mo.setResult('tip', 'maybe is script') ftlog.info('maybe is script userId =', userId) router.sendToUser(mo, userId) return mo.setResult('action', 'getDaysReward') mo.setResult('checkinDateList', [ d.strftime('%Y%m%d') for d in MonthCheckinStatus.checkinDateList ]) daysRewards = [] for days, rewardContent in enumerate(monthcheckin.getConf().get( 'daysRewards', [])): reward = rewardContent.get('reward') monthRange = monthcheckin.getMonthRange() if rewardContent.get('days') < monthRange: monthRange = rewardContent.get('days') daysRewards.append({ 'days': monthRange, 'desc': reward.get('desc'), 'picUrl': reward.get('picUrl'), 'state': self.calcDaysRewardState(MonthCheckinStatus, monthRange) }) ftlog.debug('doGetDaysRewardMonth daysRewards monthRange =', monthRange) mo.setResult('daysRewards', daysRewards) mo.setResult('supplementCheckinDateList', [ d.strftime('%Y%m%d') for d in MonthCheckinStatus.supplementCheckinDateList ]) mo.setResult('rewardDaysList', MonthCheckinStatus.rewardDaysList) ftlog.debug('doGetDaysRewardMonth userId =', userId, 'gameId =', gameId, 'clientId =', clientId, 'daysRewards =', daysRewards) router.sendToUser(mo, userId) datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'getDaysReward') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.warn('doGetDaysRewardMonth ' + str(e))
def makeProductDeliveryFailResponse(cls): mo = MsgPack() mo.setCmd('prod_delivery') fail = hallstore.storeSystem.deliveryConf.get('fail', {}) mo.setResult('info', fail.get('title', u'很抱歉,添加物品失败啦!')) mo.setResult('content', fail.get('content', u'请尽快联系我们的客服,我们一定会第一时间处理')) mo.setResult('tips', fail.get('tips', u'如有问题请拨打客服电话')) mo.setError(1, u'很抱歉,添加物品失败啦!') return mo
def doGdssListItem(self): mo = MsgPack() ec, result = self.checkCode() if ec == 0: ec, result = item_remote.listItem() if ec != 0: mo.setError(ec, result) else: mo.setResult('items', result) return mo
def _do_room__giveup(self, msg): userId = msg.getParam('userId') if not self.match.giveup(userId): roomId = msg.getParam('roomId') room = gdata.rooms()[roomId] player = room.match.findPlayer(userId) if player and not player.isQuit: mo = MsgPack() mo.setCmd('room') mo.setError(-1, '不能退出比赛') router.sendToUser(mo, userId)
def doGdssRemoveUserItem(self, userId, itemId, intEventParam): mo = MsgPack() ec, result = self.checkCode() if ec == 0: if userdata.checkUserData(userId): ec, result = item_remote.removeUserItem(HALL_GAMEID, userId, itemId, "GM_ADJUST", intEventParam) else: ec, result = 2, 'userId error !!' if ec != 0: mo.setError(ec, result) return mo
def notifyMatchGiveupFailed(self, player, message): ''' 通知用户放弃比赛失败 ''' try: msg = MsgPack() msg.setCmd('room') msg.setError(-1, message) router.sendToUser(msg, player.userId) except: ftlog.error()
def sendEnterGameError(userId, gameId, clientId, errCode, errInfo): ''' 返回错误消息 ''' mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'enter_game_after_login') mo.setResult('clientId', clientId) mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setError(errCode, errInfo) router.sendToUser(mo, userId)
def newErrorMsgPack(errCode, edrrInfo): ''' 快速工具, 依据当前接收的命令, 生成一个返回错误信息的MsgPack ''' mi = getMsgPack() mo = MsgPack() mo.setCmd(mi.getCmd()) action = mi.getParam('action') if action: mo.setParam('action', action) mo.setError(errCode, edrrInfo) return mo
def doSupCheckinMonth(self, gameId, userId, clientId): try: mo = MsgPack() typeData, status = monthcheckin.supplementCheckin(userId, gameId, clientId) mo.setCmd('month_checkin') if not status: mo.setResult('userId', userId) mo.setResult('tip', 'maybe is script') ftlog.info('maybe is script userId =', userId) router.sendToUser(mo, userId) return if typeData == 1: mo.setResult('action', 'supCheckin') mo.setResult('lessCard', status['lessCard']) router.sendToUser(mo, userId) else: mo.setResult('action', 'supCheckin') mo.setResult('supCheckinCount', monthcheckin.getSupplementCheckinCardCount(userId, gameId)) mo.setResult('checkinDateList', [d.strftime('%Y%m%d') for d in status.checkinDateList]) mo.setResult('supplementCheckinDateList', [d.strftime('%Y%m%d') for d in status.supplementCheckinDateList]) mo.setResult('rewardDaysList', status.rewardDaysList) daysRewards = [] for _days, rewardContent in enumerate(monthcheckin.getConf().get('daysRewards', [])): reward = rewardContent.get('reward') monthRange = monthcheckin.getMonthRange() if rewardContent.get('days') < monthRange: monthRange = rewardContent.get('days') daysRewards.append({ 'days': monthRange, 'desc': reward.get('desc'), 'picUrl': reward.get('picUrl'), 'state': self.calcDaysRewardState(status, monthRange) }) ftlog.debug('doSupCheckinMonth daysRewards monthRange =', monthRange) mo.setResult('daysRewards', daysRewards) mo.setResult('descSucess', '恭喜你获得500金币+1幸运卡') ftlog.debug('doSupCheckinMonth usereId =', userId , 'gameId =', gameId , 'clientId =', clientId , 'checkinDateList =', [d.strftime('%Y%m%d') for d in status.checkinDateList] , 'supplementCheckinDateList =', [d.strftime('%Y%m%d') for d in status.supplementCheckinDateList]) router.sendToUser(mo, userId) datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'supCheckin') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.debug('dosupCheckin ' + str(e))
def doGdssQueryStore(self, userId, clientId): mo = MsgPack() ec, result = self.checkCode() if ec != 0: mo.setError(ec, result) else: if userdata.checkUserData(userId): tabs = StoreHelper.getStoreTabs(HALL_GAMEID, userId, clientId) mo.setResult('tabs', tabs) else: mo.setError(2, 'userId error !!') return mo
def do_gdss_query_FriendTable_Info(self, tableId0): moCheck = MsgPack() ec, result = self.checkCode() if ec: moCheck.setError(ec, result) return from freetime.util import log as ftlog ftlog.debug('HALLAdmin.queryFriendTableInfo tableId:', tableId0) from hall.entity import hall_friend_table params = hall_friend_table.getFriendTableInfo(str(tableId0)) return params
def doSetChatPunish(self, userId, punishState): """ GM工具设置玩家聊天惩罚状态 """ mo = MsgPack() ec, result = self.checkCode() if ec == 0: result = user_system.setChatPunish(userId, punishState) if ec != 0: mo.setError(ec, result) else: mo.setResult("code", result) return mo
def doEnter(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_enter') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.roomId) mo.setResult('userId', userId) try: if not self.match.enter(userId): mo.setError(1, u'比赛已经下线') except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo)
def doGdssListUserItem(self, userId): mo = MsgPack() ec, result = self.checkCode() if ec == 0: if userdata.checkUserData(userId): ec, result = item_remote.listUserItem(userId) else: ec, result = 2, 'userId error !!' if ec != 0: mo.setError(ec, result) else: mo.setResult('items', result) return mo
def doGdssQueryAds(self, userId, clientId): mo = MsgPack() ec, result = self.checkCode() if ec != 0: mo.setError(ec, result) else: adsTemplate = hallads.queryAds(HALL_GAMEID, 10001, clientId) if adsTemplate: mo.setResult('name', adsTemplate.name) mo = AdsHelper.encodeAdsTemplate(HALL_GAMEID, 10001, clientId, adsTemplate) else: mo.setResult('name', None) return mo
def doRemoveUserMail(self, userId, mailId): """ GM工具删除玩家邮件接口 """ mo = MsgPack() ec, result = self.checkCode() if ec == 0: result = user_rpc.removeUserMail(userId, mailId) if ec != 0: mo.setError(ec, result) else: mo.setResult("mails", result) return mo
def doGdssAddVipExp(self, userId, toAddExp): mo = MsgPack() ec, result = self.checkCode() if ec == 0: if userdata.checkUserData(userId): ec, result = user_remote.addVipExp(HALL_GAMEID, userId, toAddExp, 'GM_ADJUST', 0) else: ec, result = 2, 'userId error !!' if ec != 0: mo.setError(ec, result) else: mo.setResult('vipExp', result) return mo
def doUpdateMonthCheckin(self, gameId, userId, clientId): try: mo = MsgPack() mo.setCmd('month_checkin') status = monthcheckin.loadStatus(userId) mo.setResult('curDate', status.curDate.strftime('%Y%m%d')) mo.setResult('checkinDates', [d.strftime('%Y%m%d') for d in status.checkinDateList]) mo.setResult('supCheckinDates', [d.strftime('%Y%m%d') for d in status.supplementCheckinDateList]) mo.setResult('rewardDaysList', status.rewardDaysList) daysRewards = [] for _days, rewardContent in enumerate(monthcheckin.getConf().get('daysRewards', [])): reward = rewardContent.get('reward') monthRange = monthcheckin.getMonthRange() if rewardContent.get('days') < monthRange: monthRange = rewardContent.get('days') daysRewards.append({ 'days': monthRange, 'desc': reward.get('desc'), 'picUrl': reward.get('picUrl'), 'state': self.calcDaysRewardState(status, monthRange) }) ftlog.debug('doUpdateMonthCheckin daysRewards monthRange =', monthRange) mo.setResult('daysRewards', daysRewards) checkinRewardMap = monthcheckin.getConf().get('checkDesc', {}) mo.setResult('specailDate', monthcheckin.getNowSpecailDate(status.curDate.strftime('%Y%m%d'))) mo.setResult('checkinRewardImg', checkinRewardMap.get('picUrl')) mo.setResult('checkinRewardDesc', checkinRewardMap.get('desc', '500金币+1幸运卡')) activies = [] for _days, rewardContent in enumerate(monthcheckin.getConf().get('activies', [])): activies.append({ 'date': rewardContent.get('date'), 'tip': rewardContent.get('tip') }) mo.setResult('activies', activies) mo.setResult('action', 'update') mo.setResult('supCheckinCount', monthcheckin.getSupplementCheckinCardCount(userId, gameId)) ftlog.debug('doUpdateMonthCheckin userId =', userId , 'gameId =', gameId , 'clientId =', clientId , 'curDate =', status.curDate.strftime('%Y%m%d') , 'checkinDates =', [d.strftime('%Y%m%d') for d in status.checkinDateList] , 'supCheckinDates =', [d.strftime('%Y%m%d') for d in status.supplementCheckinDateList]) router.sendToUser(mo, userId) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'update') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.warn('doupdate ' + str(e))
def doBuyProductOld(self, gameId, userId, prodId): mo = MsgPack() mo.setCmd('buy_prod') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('prodId', prodId) try: clientId = sessiondata.getClientId(userId) orderId = self._makeOrderId(gameId, userId, prodId) hallstore.storeSystem.buyProduct(gameId, userId, clientId, orderId, prodId, 1) mo.setResult('orderId', orderId) router.sendToUser(mo, userId) except TYBizException, e: mo.setError(e.errorCode, e.message)
def handlerHttpRequest(httprequest): """ HTTP请求处理总入口 """ rpath = httprequest.path try: session = stackless.getcurrent()._fttask.session session['ishttp'] = 1 if TRACE_RESPONSE: ftlog.info('HTTPREQUEST', rpath, httprequest.args) # 当前服务处理 markParams = _http_path_methods.get(rpath, None) if markParams == None: __handlerHttpStatic(httprequest) return # 查找静态资源返回 # IP 地址过滤 fun_ip_filter = markParams['fun_ip_filter'] if fun_ip_filter: ip = getClientIp() mo = fun_ip_filter(ip) if mo: mo = __stringifyResponse(markParams['jsonp'], mo, markParams['content_type']) doFinish(mo, markParams['content_type']) return # IP 过滤失败, 返回 # 执行动态调用 try: handler = markParams['handler'] fun_method = markParams['fun_method'] mo, values = _checkRequestParams(handler, markParams['paramkeys']) if not mo: # 参数检测, 没有错误 mo = fun_method(*values) if mo is None: mo = MsgPack() mo.setCmd(rpath) mo.setError(1, 'http api return None') except Exception, e: ftlog.error() mo = MsgPack() mo.setCmd(rpath) mo.setResult('Exception', str(e)) mo.setError(1, 'http api exception') mo = __stringifyResponse(markParams['jsonp'], mo, markParams['content_type']) doFinish(mo, markParams['content_type'], rpath)
def doConsumeTransaction(self, appId, userId, prodId, clientId, prodCount, prodOrderId): mo = MsgPack() mo.setCmd('buy_prod') mo.setResult('appId', appId) mo.setResult('userId', userId) mo.setResult('prodId', prodId) mo.setResult('prodCount', prodCount) mo.setResult('prodOrderId', prodOrderId) if not prodOrderId: mo.setError(1, 'not prodOrderId') else: try: hallstore.storeSystem.buyProduct(appId, userId, clientId, prodOrderId, prodId, prodCount) except TYStoreException, e: mo.setError(e.errorCode, e.message) except:
def doGetDaysRewardMonth(self, gameId, userId, clientId): msg = runcmd.getMsgPack() days = msg.getParam('days') try: mo = MsgPack() MonthCheckinStatus = monthcheckin.getDaysReward(userId, days, gameId) mo.setCmd('month_checkin') if not MonthCheckinStatus: mo.setResult('userId', userId) mo.setResult('tip', 'maybe is script') ftlog.info('maybe is script userId =', userId) router.sendToUser(mo, userId) return mo.setResult('action', 'getDaysReward') mo.setResult('checkinDateList', [d.strftime('%Y%m%d') for d in MonthCheckinStatus.checkinDateList]) daysRewards = [] for days, rewardContent in enumerate(monthcheckin.getConf().get('daysRewards', [])): reward = rewardContent.get('reward') monthRange = monthcheckin.getMonthRange() if rewardContent.get('days') < monthRange: monthRange = rewardContent.get('days') daysRewards.append({ 'days': monthRange, 'desc': reward.get('desc'), 'picUrl': reward.get('picUrl'), 'state': self.calcDaysRewardState(MonthCheckinStatus, monthRange) }) ftlog.debug('doGetDaysRewardMonth daysRewards monthRange =', monthRange) mo.setResult('daysRewards', daysRewards) mo.setResult('supplementCheckinDateList', [d.strftime('%Y%m%d') for d in MonthCheckinStatus.supplementCheckinDateList]) mo.setResult('rewardDaysList', MonthCheckinStatus.rewardDaysList) ftlog.debug('doGetDaysRewardMonth userId =', userId , 'gameId =', gameId , 'clientId =', clientId , 'daysRewards =', daysRewards) router.sendToUser(mo, userId) datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc']) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'getDaysReward') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.warn('doGetDaysRewardMonth ' + str(e))
def _onEnterRoomFailed(cls, msg, checkResult, userId, gameId, clientId, roomId=0): '''进入房间失败回调函数''' ftlog.warn("|userId, reason, roomId:", userId, checkResult, roomId, caller=cls) # 调用最小房间金币不够充值提醒的todotask if not roomId: roomId = msg.getParam('candidateRoomId', 0) if checkResult == TYRoom.ENTER_ROOM_REASON_LESS_MIN or checkResult == 104: from hall.entity import hallproductselector product, _ = hallproductselector.selectLessbuyProduct(gameId, userId, clientId, roomId) if product: from hall.entity.todotask import TodoTaskOrderShow todotask = TodoTaskOrderShow.makeByProduct("金币不够啦,买一个超值礼包吧!", "", product) if todotask: TodoTaskHelper.sendTodoTask(gameId, userId, todotask) mo = MsgPack() mo.setCmd('quick_start') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setError(checkResult, '进入房间失败,请稍后重试') router.sendToUser(mo, userId)
def doGetMessage(self, gameId, userId, clientId): msg = runcmd.getMsgPack() state = msg.getParam('state') isFirst = msg.getParam('isFirst') try: mo = MsgPack() result = monthcheckin.doMessage(userId, gameId, clientId, state, isFirst) mo.setCmd('month_checkin') mo.setResult('userId', userId) mo.setResult('result', result) mo.setResult('gameId', gameId) mo.setResult('action', 'getMessage') router.sendToUser(mo, userId) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'getMessage') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.warn('doGetMessage ' + str(e))
def doGetFirstRechargeReward(self, gameId, userId, clientId): if not hallstore.isFirstRecharged(userId): mo = MsgPack() mo.setCmd('get_first_recharge') mo.setError(-1, '你还没有首充!') router.sendToUser(mo, userId) return if not hallstore.setFirstRechargeReward(userId): mo = MsgPack() mo.setCmd('get_first_recharge') mo.setError(-1, '您已经领取了!') router.sendToUser(mo, userId) return timestamp = pktimestamp.getCurrentTimestamp() userAssets = hallitem.itemSystem.loadUserAssets(userId) itemKindId = hall_first_recharge.queryFirstRecharge(gameId, userId, clientId) assetKindId = hallitem.itemIdToAssetId(itemKindId) balance = userAssets.balance(gameId, assetKindId, timestamp) if balance <= 0: userAssets.addAsset(gameId, assetKindId, 1, timestamp, 'FIRST_RECHARGE', 0) ftlog.info('SotreTcpHandler.doGetFirstRechargeReward gameId=', gameId, 'userId=', userId, 'itemId=', itemKindId) userBag = userAssets.getUserBag() item = userBag.getItemByKindId(itemKindId) if item: try: userBag.doAction(gameId, item, 'open', timestamp) except: ftlog.error('SotreTcpHandler.doGetFirstRechargeReward gameId=', gameId, 'userId=', userId, 'itemId=', itemKindId) pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_PRIVATE, userId, '恭喜您获得首充豪华大礼包奖励!') datachangenotify.sendDataChangeNotify(gameId, userId, ['item', 'promotion_loc'])
def doItemUseOld(self, gameId, userId, itemId, clientId): try: # 老版本只认30这个itemId if itemId == 30: itemId = 2003 itemId = ItemHelper.translateItemId(gameId, 9999, itemId) userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag() item = self._ensureItemExistsOld(userBag, itemId) actionName = ItemHelper.translateUseActionName(item) if actionName: actionResult = userBag.doAction(gameId, item, actionName) router.sendToUser(ItemHelper.makeDoActionResponse(gameId, userId, actionResult), userId) router.sendToUser(ItemHelper.makeItemListResponse(gameId, userId), userId) else: mo = MsgPack() mo.setCmd('bag') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('itemId', itemId) mo.setError(-1, '该道具不能使用') router.sendToUser(mo, userId) except TYBizException, e: self.handleException(itemId, gameId, userId, clientId, e)
def doHelloTuyou(self): gameId = runhttp.getParamInt('gameId') clientId = runhttp.getParamStr('clientId', '') ftlog.debug('Hello->gameId=', gameId, 'clientId=', clientId) mo = MsgPack() mo.setCmd('hello') if gameId not in gdata.gameIds(): mo.setError(1, 'gameId error !') return mo clientIdInt = pokerconf.clientIdToNumber(clientId) if clientIdInt <= 0: mo.setError(2, 'clientId error !') return mo nicaiCode = runhttp.getParamStr('nicaiCode', '') if not nicaiCode: mo.setError(3, 'nicai error !') return mo # 1. 生存你猜CODE HelloTuyou.getNiCaiCode(mo, nicaiCode) # 2. 取得更新信息 updateVersion = runhttp.getParamInt('updateVersion') alphaVersion = runhttp.getParamInt('alphaVersion', 0) HelloTuyou.getUpdataInfo(mo, gameId, clientId, updateVersion, alphaVersion) # 3. 静态配置文件的MD5和URL staticConf = hallconf.getUpgradeStaticConf() mo.updateResult(staticConf) # 4. 返回三方SDK的控制开关 HelloTuyou.getThirdSwitches(mo, clientId) # 设置其他返回值 mo.setResult('gameId', gameId) mo.setResult('clientId', clientId) return mo
def doGenerateCode(cls, paramsDict): VALIDS_CODE_TYPE = ['ct_normal', 'ct_number'] clientIds = paramsDict.get('client_ids', '[]') begin_time = paramsDict.get('begin_time', '') end_time = paramsDict.get('end_time', '') rewards = paramsDict.get('rewards', '[]') count = paramsDict.get('count', 0) unique = paramsDict.get('unique', 0) # 新增参数 游戏ID 两位 20160412 useGameId = paramsDict.get('useGameId', 0) # 新增参数 推广人ID 就是用户ID promoteId = paramsDict.get('promoteId', 0) codeType = paramsDict.get('codeType', 'ct_normal') ftlog.info('ExchangeCode->doGenerateCode clientids=', clientIds, 'begin_time=', begin_time, 'end_time=', end_time, 'rewards=', rewards, 'count=', count, 'unique=', unique, 'codeType=', codeType, 'useGameId=', useGameId, 'promoteId=', promoteId) mo = MsgPack() ec, clientIds = cls.decodeClientIds(clientIds) if ec != 0: mo.setError(ec, clientIds) return mo ec, rewards = cls.decodeRewards(rewards) if ec != 0: mo.setError(ec, rewards) return mo try: count = int(count) if count <= 0: mo.setError(1, 'count必须是>0的整数') return mo except: mo.setError(1, 'count必须是>0的整数') return mo try: unique = int(unique) if unique not in (0, 1): mo.setError(1, 'unique必须是0或1的整数') return mo except: mo.setError(1, 'unique必须是0或1的整数') return mo try: unique = int(unique) if unique not in (0, 1): mo.setError(1, 'unique必须是0或1的整数') return mo except: mo.setError(1, 'unique必须是0或1的整数') return mo if codeType not in VALIDS_CODE_TYPE: mo.setError(1, 'codeType必须在%s中' % (VALIDS_CODE_TYPE)) return mo try: datetime.strptime(begin_time, '%Y-%m-%d %H:%M:%S') except: mo.setError(1, 'begin_time必须是时间字符串') return mo try: datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S') except: mo.setError(1, 'end_time必须是时间字符串') return mo nowDate = datetime.now().date() seqCount, seriesCode, codeList = cls.generateCodes(nowDate, codeType, count, useGameId) readyKey = 'excodeready:%s' % (seriesCode) for code in codeList: daobase.executeMixCmd('SADD', readyKey, code) # 通用配置 common_ = { 'begin_time': begin_time, 'end_time': end_time, 'client_ids': clientIds, 'generate_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'unique': unique, 'seqCount': seqCount, 'useGameId': useGameId, 'promoteId': promoteId } daobase.executeMixCmd('HSET', 'excodeinfo:' + seriesCode, 'common', json.dumps(common_)) daobase.executeMixCmd('HSET', 'excodeinfo:' + seriesCode, 'rewards', json.dumps(rewards)) mo.setResult('common', common_) mo.setResult('rewards', rewards) mo.setResult('excodes', codeList) ftlog.info('ExchangeCode->doGenerateCode', 'mo=', mo) return mo
def doGenerateCodeOld(cls, paramsDict): mo = MsgPack() clientIds = paramsDict.get('client_ids', '[]') begin_time = paramsDict.get('begin_time', '') end_time = paramsDict.get('end_time', '') rewards = paramsDict.get('rewards', '[]') count = int(paramsDict.get('count', 0)) unique = int(paramsDict.get('unique', 0)) version = int(paramsDict.get('version', 0)) activityId = "" if version == 2: activityId = paramsDict.get('activityId', '') if not activityId: mo.setError(1, u'缺少activityId') return mo ftlog.info('ExchangeCode->doGenerateCode', 'clientids=', clientIds, 'begin_time=', begin_time, \ 'end_time=', end_time, 'rewards=', rewards, 'count=', count, 'unique=', unique, "version=", version, "activityId=", activityId) try: clientIds = json.loads(clientIds) rewards = json.loads(rewards) except: mo.setError(1, u'clientIds或者rewards不是json格式,请重配置') return mo if len(clientIds) == 0 or len(rewards) == 0: mo.setError(1, u'必须配置生效的clientId和兑换发放奖励,请重配置') return mo if count == 0: mo.setError(1, u'至少生应成一个兑换码') return mo if version == 2: seriesCode = activityId exCodeLen = 5 wordlist = cls._wordlist2 else: seriesCode = cls.__generateSeries() exCodeLen = 10 wordlist = cls._wordlist excodeSet = set([]) while count > 0: code_ = '' for _ in xrange(exCodeLen): code_ += random.choice(wordlist) if version == 2: excode_ = code_ else: excode_ = seriesCode + code_ if excode_ not in excodeSet: excodeSet.add(excode_) count -= 1 excodeList = list(excodeSet) for i in xrange(len(excodeList)): daobase.executeMixCmd('SADD', 'excodeready:' + seriesCode, excodeList[i]) # 通用配置 common_ = { 'begin_time': begin_time, 'end_time': end_time, 'client_ids': clientIds, 'generate_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'unique': unique } daobase.executeMixCmd('HSET', 'excodeinfo:' + seriesCode, 'common', json.dumps(common_)) daobase.executeMixCmd('HSET', 'excodeinfo:' + seriesCode, 'rewards', json.dumps(rewards)) mo.setResult('common', common_) mo.setResult('rewards', rewards) mo.setResult('excodes', excodeList) ftlog.info('ExchangeCode->doGenerateCode', 'mo=', mo) return mo
mo.setError(1, 'http api return None') except Exception, e: ftlog.error() mo = MsgPack() mo.setCmd(rpath) mo.setResult('Exception', str(e)) mo.setError(1, 'http api exception') mo = __stringifyResponse(markParams['jsonp'], mo, markParams['content_type']) doFinish(mo, markParams['content_type'], rpath) except Exception, e: ftlog.error() mo = MsgPack() mo.setCmd(rpath) mo.setResult('Exception', str(e)) mo.setError(1, 'system exception return') mo = __stringifyResponse(0, mo, '') doFinish(mo, CONTENT_TYPE_HTML) def addWebRoot(webroot): ''' 添加静态资源查找路径 ''' if not webroot in _path_webroots: webroot = os.path.abspath(webroot) + os.path.sep if TRACE_RESPONSE: ftlog.info('HTTP Add WEBROOT ->', webroot) _path_webroots.append(webroot) else: if TRACE_RESPONSE:
def makeProductDeliveryErrorResponse(cls, ec, info): mo = MsgPack() mo.setCmd('prod_delivery') mo.setError(ec, info) return mo
def sendErrorResponse(cls, userId, cmd, errorCode, errorInfo): mo = MsgPack() mo.setCmd(cmd) mo.setError(errorCode, errorInfo) router.sendToUser(mo, userId) return mo