def parseData(self, data): msg = MsgPack() try: msg.unpack(data) return msg except: raise Exception('the json data error 1 !! [' + repr(data) + ']')
def lostHandler(self, reason): if self.robotUser: mi = MsgPack() mi.setCmd('_tcp_closed_') self.robotUser.msgQueue.append(mi) else: pass
def doGetDescription(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_des') mo.setResult('gameId', self.gameId) self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
def doGetMessageCount(self, gameId, userId): mo = MsgPack() privateCount = pkmessage.getPrivateUnReadCount(gameId, userId) globalCount = pkmessage.getGlobalUnReadCount(gameId, userId) mo.setResult('counts', {'global': globalCount, 'private': privateCount, 'led': 0}) mo.setResult('ok', 'true') return mo
def doUserSetStarId(self, userId, gameId, clientId, starId): userdata.setAttr(userId, 'starid', starId) mo = MsgPack() mo.setCmd('set_star_id') mo.setResult('gameId', gameId) mo.setResult('starId', starId) router.sendToUser(mo, userId)
def doQiPaiNotify(self, appId, userId, buttonId, rmbs, diamonds): userdata.clearUserCache(userId) if appId > 0 and userId > 0: datachangenotify.sendDataChangeNotify(appId, userId, ['chip', 'diamonds']) msg = MsgPack() msg.setResult('ec', 0) return msg
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 doRoomReturnQueue(self, roomId, userId): msg = runcmd.getMsgPack() ftlog.debug('msg=', msg, caller=self) gdata.rooms()[roomId].doReturnQueue(userId) mo = MsgPack() mo.setCmd('room') mo.setResult('action', 'return_queue') router.responseQurery(mo)
def doGetDescription(self, userId): if ftlog.is_debug(): ftlog.debug('TYRelaxationMatchRoom.doGetDescription', 'userId=', userId) mo = MsgPack() mo.setCmd('m_des') mo.setResult('gameId', self.gameId) self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
def doRoomLeaveMatch(self, roomId, userId): msg = runcmd.getMsgPack() ftlog.debug('msg=', msg, caller=self) tableId = msg.getParam("tableId", 0) gdata.rooms()[roomId].doLeaveMatch(userId, tableId) mo = MsgPack() mo.setCmd('room') mo.setResult('action', 'leave_match') router.responseQurery(mo)
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 doGetDescription(self, userId): if self._logger.isDebug(): self._logger.debug('TYGroupMatchRoom.doGetDescription', 'userId=', userId) mo = MsgPack() mo.setCmd('m_des') mo.setResult('gameId', self.gameId) self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
def lostHandler(self, reason): if self.robotUser: # ftlog.debug('RobotClientProtocol.lostHandler', reason, self.robotUser.snsId) mi = MsgPack() mi.setCmd('_tcp_closed_') self.robotUser.msgQueue.append(mi) else: # ftlog.debug('RobotClientProtocol.lostHandler robot user is none !!') pass
def onMsg(self): if self.robotUser: pack = stackless.getcurrent()._fttask.pack # ftlog.debug('RobotClientProtocol.onMsg', self.robotUser.snsId, '[' + pack + ']') msg = MsgPack() msg.unpack(pack) self.robotUser.msgQueue.append(msg) else: # ftlog.debug('RobotClientProtocol.onMsg robot user is none !!') self.closeConnection(1)
def dataReceived(self, data): if self.encry_seed == 0: if len(data) >= 4: self.encry_seed = int(data, 16) # ftlog.debug('RobotClientProtocol.lineReceived encry_seed=', self.encry_seed) mi = MsgPack() mi.setCmd('_tcp_conneted_') self.robotUser.msgQueue.append(mi) data = data[4:] super(RobotClientProtocol, self).dataReceived(data)
def doChargeNotify(self, gameId, userId, prodId, rmbs, diamonds, clientId): if diamonds > 0: hallvip.userVipSystem.addUserVipExp(gameId, userId, diamonds, 'BUY_PRODUCT', pokerconf.productIdToNumber(prodId)) TGHall.getEventBus().publishEvent(ChargeNotifyEvent(userId, gameId, rmbs, diamonds, prodId, clientId)) mo = MsgPack() mo.setCmd('charge_notify') mo.setResult('userId', userId) mo.setResult('gameId', gameId) return mo
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 __notifyRobotSigninMatch(self, player): ftlog.debug("<< |roomId, instId, playerId :", self.roomId, player.inst.instId, player.userId, caller=self) # if hasattr(player.inst, "calledRobot") : #同一个比赛实例只召唤一次机器人 # return if player.inst.state >= player.inst.STATE_PREPARE: return if self.roomConf.get('hasrobot'): # player.inst.calledRobot = True #同一个比赛实例只召唤一次机器人 startConf = player.inst.conf.start if self.roomConf["robotUserMaxCount"] == -1: if startConf.isTimingType(): minsize = startConf.userMinCount else: minsize = startConf.userCount - 2 else: minsize = self.roomConf["robotUserMaxCount"] cur_p = len(player.inst.playerMap) if cur_p >= minsize: return mo = MsgPack() mo.setCmd('robotmgr') mo.setAction('callmatch') mo.setParam('gameId', self.gameId) mo.setParam('roomId', self.roomId) mo.setParam('robotCount', 4) router.sendRobotServer(mo, player.userId) func = functools.partial(self.__notifyRobotSigninMatch, player) FTTimer(15, func)
def makeDecroationQueryResponseV3_7(cls, gameId, userId): mo = MsgPack() mo.setCmd('decoration') mo.setResult('action', 'query') mo.setResult('userId', userId) mo.setResult('itemIds', cls.queryUserWeardItemKindIds(gameId, userId)) return mo
def doGetTaskReward(self, gameId, userId, taskId): ''' 获取活动奖励 ''' try: timestamp = pktimestamp.getCurrentTimestamp() taskModel = neituiguangtask.newUserTaskSystem.loadTaskModel(userId, timestamp) task = taskModel.userTaskUnit.findTask(taskId) if not task: raise TYBizException(-1, '未知的任务:%s' % (taskId)) expiresTime = self.calcTaskExpires(userId) if timestamp >= expiresTime: raise TYBizException(-1, '任务已经过期') if not userdata.getAttr(userId, 'bindMobile'): conf = neituiguang.getConf() TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskBindPhone(conf.pleaseBindPhone, '')) return assetList = neituiguangtask.newUserTaskSystem.getTaskReward(task, timestamp, 'PROMOTE_TASK', taskId) router.sendToUser(self.buildTaskInfoResponse(userId), userId) rewardStr = TYAssetUtils.buildContentsString(assetList) mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'get_task_reward') mo.setResult('code', 0) mo.setResult('info', '恭喜您获得了%s' % rewardStr) router.sendToUser(mo, userId) except TYBizException, e: router.sendToUser(self.makeErrorResponse('get_task_reward', e.errorCode, e.message), userId)
def makeErrorResponse(cls, action, errorCode, info): mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', action) mo.setResult('code', errorCode) mo.setResult('info', info) return mo
def _handlerRpcCommand(markParams, msg): handler = markParams['handler'] fun_method = markParams['fun_method'] argl = msg.getParam('argl') argd = msg.getParam('argd') ret = fun_method(handler, *argl, **argd) if markParams['syncCall']: mo = MsgPack() mo.setKey('result', ret) router.responseQurery(mo, 'QR')
def sendItemListResponse(cls, gameId, userId, tabs): mo = MsgPack() mo.setCmd('user') mo.setResult('action', 'majiang_item') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('items', cls.queryUserItemTabsV3_7(gameId, userId)) router.sendToUser(mo, userId)
def makeAdsQueryResponse(cls, gameId, userId, clientId, adsTemplate): mo = MsgPack() mo.setCmd('ads') mo.setResult('action', 'query') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('ads', cls.encodeAdsTemplate(gameId, userId, clientId, adsTemplate)) return mo
def doUpdateItem(self, gameId, userId): mo = MsgPack() mo.setCmd('exchange') mo.setResult('action', 'update_item') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('item_list', ExchangeHelper.encodeCouponItemList(self._getCouponService().couponItems)) router.sendToUser(mo, userId)
def makeRouletteQueryResponse(cls, gameId, userId, clientId, action, rouletteTemplate): mo = MsgPack() mo.setCmd('game') mo.setResult('action', action) mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('result', rouletteTemplate) return mo
def makeItemListResponseByGame(cls, gameId, userId): mo = MsgPack() mo.setCmd('item') mo.setResult('action', 'list_by_game') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('tabs', cls.queryUserItemTabsByGame(gameId, userId)) return mo
def makeDoActionResponse(cls, gameId, userId, actionResult): mo = MsgPack() mo.setCmd('bag') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('action', 'open') mo.setResult('info', actionResult.message) return mo
def createMsgPackRequest(self, cmd, action=None): mp = MsgPack() mp.setCmd(cmd) if action: mp.setParam('action', action) mp.setParam('gameId', self.table.gameId) mp.setParam('roomId', self.table.roomId) mp.setParam('tableId', self.table.tableId) return mp
def sendChangeBetsConfReq(cls, shadowRoomId, betsConf): mpReq = MsgPack() mpReq.setCmd("room") mpReq.setParam("action", "change_betsConf") mpReq.setParam("roomId", shadowRoomId) mpReq.setParam("betsConf", betsConf) if ftlog.is_debug(): ftlog.debug(str(mpReq), caller=cls) router.sendTableServer(mpReq, shadowRoomId)
def doGetPrize(cls, gameId, userId, clientId, action): ''' 新用户领奖接口 ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() bindmobile = userdata.getAttr(userId, 'bindMobile') userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) if cls.bindOk(bindmobile): prizeGet = cls.sendBothUserPrize(gameId, userId, userstate, conf) if prizeGet == -1: # 用户状态错误 NeiTuiGuangProtocolBuilder.buildBasicInfo( 2, action, "用户状态错误", mo) else: # 发送奖励成功 NeiTuiGuangProtocolBuilder.buildBasicInfo( 0, action, cls.getprize(gameId, 0, conf, prizeGet), mo) else: # 未绑定手机 NeiTuiGuangProtocolBuilder.buildBasicInfo( 1, action, cls.getprize(gameId, 2, conf), mo) return mo
def doOldUserGetPrize(cls, gameId, userId, friendId, clientId, action): ''' 老用户领奖接口 ''' conf = hallconf.getNeiTuiGuangConf(clientId) if not conf: ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'action=', action) return mo = MsgPack() mpush = None userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state) bindmobile = userdata.getAttr(userId, 'bindMobile') if userstate == 2: if cls.bindOk(bindmobile): prizeGet = cls.sendOldUserPrize(userId, friendId, gameId, conf) NeiTuiGuangProtocolBuilder.buildOldUserPrize( 0, action, cls.getprize(gameId, 0, prizeGet), friendId, mo) ##### 推一条用户奖励信息 mpush = cls.doQueryPrize(gameId, userId, clientId, action) else: NeiTuiGuangProtocolBuilder.buildBindPrize( 1, action, cls.getprize(gameId, 2), friendId, mo) else: NeiTuiGuangProtocolBuilder.buildBasicInfo( 2, action, 'user state error: not support', mo) return mo, mpush
def __init_basic_msg(self, cmd, action=None): """ 初始化消息基础 (private api) @param cmd: 协议command @param action: 协议子command名 {cmd:"command", result:{ action:"sub command"}} """ mp = MsgPack() mp.setCmd(cmd) if action: mp.setResult('action', action) mp.setResult('gameId', self.gameId) mp.setResult('roomId', self.roomId) mp.setResult('tableId', self.tableId) return mp
def doGetMessage(self, gameId, userId, msgtype, pageNo): mo = MsgPack() if msgtype == -1 or msgtype == 0: data = pkmessage.getPrivate(gameId, userId, pageNo) mo.setResult('private', data) if msgtype == -1 or msgtype == 1: data = pkmessage.getGlobal(gameId, userId, pageNo) mo.setResult('global', data) if msgtype == -1 or msgtype == 2: data = hallled.getLedMsgList(gameId) mo.setResult('led', data) mo.setResult('ok', 'true') return mo
def makePromotionUpdateResponse(cls, gameId, userId, clientId, promoteList): mo = MsgPack() mo.setCmd('promotion_loc') mo.setResult('action', 'update') mo.setResult( 'promotions', cls.encodePromoteList(gameId, userId, clientId, promoteList)) return mo
def doHallLocalNotification(self, userId, gameId, clientId): lnConfig = halllocalnotification.queryLocalNotification( gameId, userId, clientId) mo = MsgPack() mo.setCmd('hall_local_notification') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('notifies', lnConfig) router.sendToUser(mo, userId)
def _onEnterCreateRoomFailed(cls, checkResult, userId, gameId, clientId, roomId=0): '''进入创建房间失败回调函数''' ftlog.warn("|userId, reason, roomId:", userId, checkResult, roomId, caller=cls) mo = MsgPack() mo.setCmd('quick_start') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('reason', checkResult) router.sendToUser(mo, userId)
def sendAddGroupMsg(self, groups, userIds): """ 发送新增鱼群消息 """ msg = MsgPack() msg.setCmd("add_group") msg.setResult("gameId", FISH_GAMEID) msg.setResult("groups", groups) GameMsg.sendMsg(msg, userIds)
def doGetMasterTableList(self, userId, clientId): '''为了效率,贵宾室所有桌子放在一个GT进程里, 在此进程中通过遍历来获取每张桌子的状态 ''' msgRes = MsgPack() msgRes.setCmd("game") msgRes.setResult("action", "master_table_list") msgRes.updateResult( self._getVipTableList(userId, clientId, tag="", isMasterRoom=True)) router.sendToUser(msgRes, userId)
def doLeave(self, userId, msg): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_leave') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.roomId) mo.setResult('userId', userId) self.match.leave(userId) router.sendToUser(mo, userId)
def doCheckCode(self, gameId, userId, clientId, promoteCode): ''' 确立推广关系,也就是领取红包 校验通过 设置推荐人 将用户加到推荐人的推广员名单里 ''' try: timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) # 检查是否能成为推荐人 # 转到promoteCode所在的UT进程中去处理 ec, info = neituiguang_remote.canBeInviter(promoteCode, userId) if ec != 0: raise NeituiguangException(ec, info) # 设置推荐人 neituiguang.setInviter(status, promoteCode) try: # 添加invitee,此处不需要处理失败的情况,前面已经检查了 ec, info = neituiguang_remote.addInvitee( promoteCode, userId, status.isBindMobile) if ec != 0: ftlog.warn('NeiTuiGuangTcpHandler.doCheckCode gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'promoteCode=', promoteCode, 'call=', 'neituiguang_remote.addInvitee', 'ec=', ec, 'info=', info) except: ftlog.error('NeiTuiGuangTcpHandler.doCheckCode gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'promoteCode=', promoteCode, 'call=', 'neituiguang_remote.addInvitee', 'ec=', ec, 'info=', info) ftlog.hinfo('neituiguang.statics eventId=', 'INPUT_PRMOTE_CODE', 'userId=', userId, 'clientId=', clientId, 'promoteCode=', promoteCode, 'result=', 'ok') mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'code_check') mo.setResult('code', 0) router.sendToUser(mo, userId) except Exception, e: if not isinstance(e, TYBizException): ftlog.error() ec, info = (e.errorCode, e.message) if isinstance( e, TYBizException) else (-1, '系统错误') ftlog.hinfo('neituiguang.statics eventId=', 'INPUT_PRMOTE_CODE', 'userId=', userId, 'clientId=', clientId, 'promoteCode=', promoteCode, 'result=', 'failed', 'ec=', ec, 'info=', info) router.sendToUser(self.makeErrorResponse('code_check', ec, info), userId)
def doGdssAddUserItem(self, userId, kindId, count, intEventParam): mo = MsgPack() ec, result = self.checkCode() if ec == 0: if count >= 1000: ec = 1 result = 'item count to much !!' else: if userdata.checkUserData(userId): ec, result = item_remote.addUserItem( HALL_GAMEID, userId, kindId, count, "GM_ADJUST", intEventParam) else: ec, result = 2, 'userId error !!' if ec != 0: mo.setError(ec, result) return mo
def getMyFriendTableRecord(self, userId, gameId): """获取我的好友桌战绩 """ records = gamedata.getGameAttr(userId, DIZHU_GAMEID, "friendTableRecords") ftlog.debug("getMyFriendTableRecord userId =", userId, "records =", records) if records: records = json.loads(records) else: records = [] msgRes = MsgPack() msgRes.setCmd("dizhu") msgRes.setResult('gameId', gameId) msgRes.updateResult({"action": "get_ft_table_record"}) msgRes.setResult("records", records) router.sendToUser(msgRes, userId)
def encode(msgstr): if not msgstr: return msgstr if msgstr[0] != "{": return msgstr if msgstr.find('"cmdId"') < 0: return msgstr msgPack = MsgPack() msgPack.unpack(msgstr) cmdId = msgPack.getKey("cmdId") if not cmdId: return msgstr cmdObj = _getCmdObj(cmdId) if not cmdObj: return msgstr binStr = cmdObj.structMsg(msgPack) return struct.pack("!3sB", "$fs", cmdId) + binStr
def sendLocalPushTodoTask(userid, gameId, hour, minute, second, direct=True): """ 推送 本地推送push added by nick.kai.lee 向客户端推送闹钟push的注册,比如每次客户端登录时都会推送一次"本地推送的功能" Args: userid: 玩家userid cache: action命名是否是缓存形式,默认不缓存 direct: 是否直接发送,False则return dict """ if not TYPlayer.isHuman(userid): return False, None ftlog.debug('sendLocalPushTodoTask:', userid) from difang.majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder from datetime import datetime now = datetime.now() # alarm3个元素,days,seconds,microseconds, seconds遇到过去的时间会自动获得明天这个时间点的时间差 alarm = datetime(datetime.now().year, datetime.now().month, datetime.now().day, hour, minute, second) # 推送内容 import random content = random.choice([ "还记得上次在拜雀神中抽取的大奖么?机会又来了!", "修复老年痴呆,拯救弱智儿童,途游麻将提高智商值得你拥有!", "主人,您的任务奖励还没领取呢,去看看吧!", "优惠降临!充值送豪礼,下班来放松玩玩吧!", "幸运大抽奖可以免费领取金币了,快来领取吧!", "您有一份礼包未签收,快去活动中心看看吧!", "点我速领500金币~", "工作一天了,让麻将小莲帮你放松放松~", "亲,每隔10分钟1场免费定时赛,100奖券随便拿!", "您可以领取每日奖励了,它将会很快过期,快回到途游麻将领取吧!", "雀神爷爷说马上就要发红包了,你准备好了么?", "您获取的奖券兑换话费了嘛?", "大哥,您的贵宾桌我们已经为您准备好了!静候您的光临!", "您的好友邀请您一起对战途游麻将!" ]) task = MahjongTodoTaskBuilder.dict_reg_push_alarm(userid, content, (alarm - now).seconds, [True, False, True, False, True, False], "", {}, 3) if not task: return False, None ftlog.debug('sendLocalPushTodoTask:', task) if False == direct: return True, task mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userid) mo.setResult('tasks', [task]) router.sendToUser(mo, userid) return True, None
def makeDecoroationConfigResponse(cls, gameId, userId): itemKindList = hallitem.itemSystem.getAllItemKindByType( TYDecroationItemKind) mo = MsgPack() mo.setCmd('decoration') mo.setResult('action', 'config') mo.setResult( 'decroations', cls.encodeDecroationItemKindList(gameId, userId, itemKindList)) return mo
def sendVipClientId2client(gameId, userId, keyId): results = {} results['vip_clientId'] = keyId mp = MsgPack() mp.setCmd('game_vipclientId') mp.setResult('gameId', gameId) mp.setResult('userId', userId) mp.updateResult(results) router.sendToUser(mp, userId) ftlog.info("localservice|sendVipClientId2client|", gameId, userId, keyId)
def doRoomGetPlayingTableList(self, roomId): msg = runcmd.getMsgPack() ftlog.debug('msg=', msg, caller=self) result = gdata.rooms()[roomId].doGetPlayingTableList() if router.isQuery() : mo = MsgPack() mo.setCmd("room") mo.setResult("action", "playingTableList") mo.updateResult(result) router.responseQurery(mo)
def doGetDescription(self, userId): if self._logger.isDebug(): self._logger.debug("doGetDescription", "userId=", userId) mo = MsgPack() mo.setCmd("m_des") mo.setResult("gameId", self.gameId) mo.setResult("roomId", self.roomId) mo.setResult("userId", userId) self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
def doLeave(self, userId, msg): if self._logger.isDebug(): self._logger.debug('TYErdayiMatchRoom.doLeave', 'userId=', userId) mo = MsgPack() mo.setCmd('m_leave') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.roomId) mo.setResult('userId', userId) self.match.leave(userId) router.sendToUser(mo, userId)
def doNewUserRewardReceive(self, userId, gameId, clientId): ''' 领取新手启动资金 ''' isSend, startChip, _final = hallstartchip.sendStartChip(userId, gameId, clientId) mo = MsgPack() mo.setCmd('new_user_reward') mo.setResult('action', 'receive') mo.setResult('coin', startChip if isSend else 0) router.sendToUser(mo, userId)
def doListInvitee(self, gameId, userId, clientId): timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) invitee = status.encodeInvitee() mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'list_invitee') mo.setResult('invitee', invitee) router.sendToUser(mo, userId)
def _build_task_info(cls, gameid, userid, clientid): """ { "cmd": "game", "result": { "action": "task_info", "tasks": [ { "progressMax": 6, "freshTip": false, "name": "100奖券", "todotask": { "action": "pop_active_wnd", "params": { "actId": "activity_viprenwu_1123" } }, "iconUrl": "task_coupon", "state": 0, "progress": 0, "reward": "100奖券", "lblEnter": "充值", "id": 40001, "desc": "单笔充值满6元,可得100奖券" }, { "iconUrl": "task_iphoneCard", "state": -1, "freshTip": false, "id": 40002, "name": "10元话费卡" }, { "iconUrl": "task_iphoneCard", "state": -1, "freshTip": false, "id": 40003, "name": "50元话费卡" } ] } } """ tasks = [] curtime = pktimestamp.getCurrentTimestamp() # 分派任务 cls._build_single_type_task(tasks, hall_new_user_task_sys, gameid, userid, clientid, curtime) cls._build_single_type_task(tasks, hall_charge_task_sys, gameid, userid, clientid, curtime) mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'task_info') mo.setResult('tasks', tasks if tasks else []) return mo
def getShareDownloadUrl(gameId, userId, source): clientId = sessiondata.getClientId(userId) ok, clientOs, cid, special, mc, sc = parseClientIdForDL(clientId) if not ok: ftlog.warn("getShareDownloadUrl|parseClientId|error", gameId, userId, source, cid, special, mc, sc) return channels = configure.getGameJson(HALL_GAMEID, "download").get("channels", {}) channel = clientOs + '.' + special + '.' + mc + '.' + sc downloadurl = channels['default'] if channel in channels: downloadurl = channels[channel] mix_domain = [ "dspkm.cc", "lkxjv.cc", "qkpwdfo.cc", "sijas.cc", "023i.cc", "lkjsdf.cc", "vdlskm.cc", "iojpdvs.cc", "sdvnkl.cc", "owirhj.cc", "lvsdp.cc", "msvdkn.cc", "dvslkm.cc", "odnsvk.cc", "p0joefipq.cc", "mvsdpok.cc", "02r389u.cc", "sdlknv.cc", "sdfioj.cc", "klsdvm.cc" ] domainList = configure.getGameJson(HALL_GAMEID, "misc").get("mix_domain", mix_domain) replaceDict = { 'mc': mc, 'sc': sc, 'cid': str(cid), 'uid': userId, 'mixDomain': genMixDomain(domainList) } downloadurl = strutil.replaceParams(downloadurl, replaceDict) parsedUrl = urlparse.urlparse(downloadurl) qparams = urlparse.parse_qs(parsedUrl.query) if parsedUrl.query else {} qparams = {k: v[0] for k, v in qparams.iteritems()} qparams.update({'source': source}) results = {} results['action'] = 'geturl' results['downloadurl'] = urlparse.urlunparse( (parsedUrl[0], parsedUrl[1], parsedUrl[2], parsedUrl[3], urllib.urlencode(qparams), parsedUrl[5])) from freetime.entity.msg import MsgPack from poker.protocol import router mp = MsgPack() mp.setCmd('share_hall') mp.setResult('gameId', gameId) mp.setResult('userId', userId) mp.updateResult(results) router.sendToUser(mp, userId) if ftlog.is_debug(): ftlog.debug("getShareDownloadUrl|", gameId, userId, results)
def doActivityBetguessSetResult(self): ''' @param activityGameId: 6(配置里配置的哪个GameId就填哪个GameId) @param activityId: 活动ID @param issueNumber: '2016-10-31 18:20:00' @param resultState: 0,1,2 ''' try: activityGameId = runhttp.getParamInt('activityGameId') activityId = runhttp.getParamStr('activityId') issueNumber = runhttp.getParamStr('issueNumber') resultState = runhttp.getParamInt('resultState') if activityGameId == None or \ activityId == None or \ issueNumber == None or \ resultState == None: return self.makeErrorResponse('params error').pack() ftlog.debug('BetguessHttpHandler.doActivityBetguessSetResult', 'activityGameId=', activityGameId, 'activityId=', activityId, 'issueNumber=', issueNumber, 'resultState=', resultState) err, issueMap = self.getActivityIssueMapConf(activityId) if err: return err # 验证issueNumber是否存在 if issueNumber not in issueMap: return self.makeErrorResponse('issueNumber not found! issueNumber maybe error').pack() # 给活动设置竞猜结果 if not ActivityModel.updateResult(activityGameId, activityId, issueNumber, resultState): return self.makeErrorResponse('result set failed! resultState maybe error').pack() # 获得最新的活动数据 activityModel = ActivityModel.loadModel(activityGameId, activityId, issueNumber) if activityModel.resultState == activityModel.RESULT_STATE_NONE: return self.makeErrorResponse('activityModel.resultState not set!').pack() # 遍历参与玩家 chipCounter = 0 userIdList = UserRecorder.getUsers(activityGameId, activityId, issueNumber) for userId in userIdList: response = act_betguess_remote.sendRewards(userId, activityModel.countChipLeft, activityModel.countChipRight, activityModel.resultState, activityGameId, activityId, issueNumber) if response.get('err'): return self.makeErrorResponse(response.get('err')).pack() chipCounter += response.get('chip', 0) activityModel = ActivityModel.loadModel(activityGameId, activityId, issueNumber) response = MsgPack() response.setResult("activityModel", activityModel.__dict__) response.setResult('allchip', chipCounter) return response.pack() except: ftlog.error() return self.makeErrorResponse().pack()
def doDuobaoMyRewardRecord(self): ''' 一元夺宝查询我的领奖记录 ''' msg = runcmd.getMsgPack() gameId = msg.getParam("gameId") userId = msg.getParam("userId") from hall.entity import hall1yuanduobao rewardRecordList = hall1yuanduobao.duobaoRewardRecord(userId) msg = MsgPack() msg.setCmd('hall_duobao') msg.setResult('action', 'duobao_rewardRecord') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('rewardRecordList', rewardRecordList) router.sendToUser(msg, userId)
def _callRobotSigninMatch(self, count=1): self._logger.debug("MatchRoom._callRobotSigninMatch", count) for _ in xrange(count): ruid = random.randint(1, 200) # 有机器人直接进榜. if userdata.checkUserData(ruid): rname = userdata.getAttr(ruid, "name") self.addMatchRobotUser(ruid, rname) else: # 没有机器人召唤机器人登录. mo = MsgPack() mo.setCmd("robotmgr") mo.setAction("callmatch") mo.setParam("gameId", self.gameId) mo.setParam("roomId", self.roomId) mo.setParam("robotCount", 1) router.sendRobotServer(mo) self._logger.warn( "_callRobotSigninMatch, add robot failed, ruid =", ruid)
def doSignin(self, userId, signinParams, feeIndex=0): if self._logger.isDebug(): self._logger.debug('TYGroupMatchRoom.doSignin', 'userId=', userId, 'feeIndex=', feeIndex, 'signinParams=', signinParams) try: mo = MsgPack() mo.setCmd('m_signin') self.matchPlugin.ensureCanSignInMatch(self, userId, mo) signer = self.match.signin(userId, signinParams, feeIndex) if TYPlayer.isHuman(userId): self._notifyRobotSigninMatch(signer) self.reportBiGameEvent('MATCH_SIGN_UP', userId, self.roomId, 0, 0, 0, 0, 0, [], 'match_signin') except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo)
def onAgentSelfCommand(agentProtocol, src, queryid, userheader1, userheader2, message): # 处理AGENT自身的命令, 而非转发的命令 msg = MsgPack() try: msg.unpack(message) except: raise Exception('the json data error 2 !! [' + repr(message) + ']') task = FTTasklet.getCurrentFTTasklet() task.pack = msg task.run_args['src'] = src task.run_args['pack'] = msg if queryid: task.run_args['query_id'] = queryid task.run_args['userheader1'] = userheader1 task.run_args['userheader2'] = userheader2 runcmd.handlerCommand(msg)
def doGetAllRankConfs(self, gameId, userId, clientId): """ 请求所有排行榜信息 """ mo = MsgPack() mo.setCmd("fish_all_ranking") mo.setResult("gameId", gameId) mo.setResult("userId", userId) mo.setResult("allRank", ranking_system.getAllTabs(userId)) router.sendToUser(mo, userId) ftlog.debug("doGetAllRankConfs, userId =", userId, "mo =", mo)