def _notifyRobotSigninMatch(self, signer): if self._logger.isDebug(): self._logger.warn('TYGroupMatchRoom._notifyRobotSigninMatch', 'userId=', signer.userId, 'instId=', signer.inst) if self.roomConf.get('hasrobot'): startConf = self.match.matchConf.start if self.roomConf['robotUserMaxCount'] == -1: if startConf.isTimingType(): minsize = startConf.userMinCount else: minsize = startConf.userCount - 2 else: minsize = self.roomConf['robotUserMaxCount'] if signer.inst.signerCount >= minsize: return mo = MsgPack() mo.setCmd('robotmgr') mo.setAction('callmatch') mo.setParam('gameId', self.gameId) mo.setParam('roomId', self.bigRoomId) mo.setParam('robotCount', 4) router.sendRobotServer(mo, signer.userId) func = functools.partial(self._notifyRobotSigninMatch, signer) FTTimer(15, func)
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 doReceiveSdkNotify(self): """ action: add_friend accept_friend """ paramsDict = runhttp.getDict() ftlog.debug("doReceiveSdkNotify:", paramsDict) appId = paramsDict.get('appId', 0) userId = int(paramsDict.get('userId', 0)) actionType = paramsDict.get('type', '') ext = paramsDict.get('ext', None) msg = paramsDict.get('message', '') mo = MsgPack() mo.setCmd('friend_notify') mo.setResult('gameId', appId) mo.setResult('userId', userId) mo.setResult('action', actionType) mo.setResult('info', msg) if ext != None: try: extjson = json.loads(ext) for k in extjson: mo.setResult(k, extjson[k]) except: pass userdata.clearUserCache(userId) router.sendToUser(mo, userId) # if actionType == 'add_friend': # from poker.entity.biz.message import message # message.send(int(appId), message.MESSAGE_TYPE_SYSTEM, int(userId), msg) return 'success'
def doCancelCodeCheck(self, gameId, userId, clientId): ''' 取消code_check ''' try: timestamp = pktimestamp.getCurrentTimestamp() status = neituiguang.loadStatus(userId, timestamp) neituiguang.setInviter(status, 0) ftlog.hinfo('neituiguang.statics eventId=', 'CANCEL_INPUT_PRMOTE_CODE', 'userId=', userId, 'clientId=', clientId, 'result=', 'ok') mo = MsgPack() mo.setCmd('promote_info') mo.setResult('action', 'cancel_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=', 'CANCEL_INPUT_PRMOTE_CODE', 'userId=', userId, 'clientId=', clientId, 'result=', 'failed') router.sendToUser(self.makeErrorResponse('cancel_code_check', ec, info), userId)
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 sendFriendInviteTodotask(userId, invite_uid, gameId, play_mode, roomId, tableId, info_str, purl): """ 推送牌桌好友邀请的todotask * 版本 3.732 之后,改为麻将自己的todotask """ todotask = TodoTaskQuickStart(gameId, roomId, tableId) todotask.setParam('play_mode', play_mode) client_ver = sessiondata.getClientIdVer(userId) if client_ver < 3.732: show_info_ = TodoTaskShowInfo(info_str, True) show_info_.setSubCmd(todotask) msg = TodoTaskHelper.makeTodoTaskMsg(gameId, userId, show_info_) router.sendToUser(msg, userId) else: task = { 'action': 'pop_wnd_invite', 'params': { 'tasks': [todotask.toDict()], 'invite_uid': invite_uid, 'purl': purl, 'info_str': info_str } } mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('tasks', [task]) router.sendToUser(mo, 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 sendFreeChipTodoTask(userid, gameId, cache = False, direct = True): """ 推送 免费金币 added by nick.kai.lee Args: userid: 玩家userid cache: action命名是否是缓存形式,默认不缓存 direct: 是否直接发送,False则return dict """ if not TYPlayer.isHuman(userid): return False, None ftlog.debug('sendFreeChipTodoTask:', userid) from majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder task = MahjongTodoTaskBuilder.dict_free_chip(userid, cache) if not task: return False, None ftlog.debug('sendFreeChipTodoTask:', 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 sendBigMatchBackToListTodoTask(userid, gameId, cache = False, direct=True): """比赛结算界面返回按钮返回时 """ from majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder msg = "比赛已结束,点击离开按钮返回比赛列表" task = MahjongTodoTaskBuilder.dict_general_box(userid, msg, cache) retTask = strutil.cloneData(task) buttonLeaveTask = { "content":"离开", "tasks":[ { "action":"trigger_notify", "params":{ "eventName":"UPDATE_MATCH_BACK_TO_LIST" } } ] } retTask['params']['buttons'] = [buttonLeaveTask] mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userid) mo.setResult('tasks', [retTask]) router.sendToUser(mo, userid) return True, None
def sendMasterGiftTodoTask(userId, gameId, clientId, pic, pay_order, roomId): """ 推送高手礼包弹窗 @param pay_order 挑选商品模板 """ if not TYPlayer.isHuman(userId): return product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, pay_order) if not product: ftlog.error('userId =', userId, 'clientId =', clientId, 'pay_order =', pay_order, 'can not find suitable product!') return todotask = TodoTaskPayOrder(product) task = { 'action': 'cache_wnd_gaoshou', 'params': { 'pic': pic, 'tasks': [todotask.toDict()] } } mo = MsgPack() mo.setCmd('majiang_todotasks') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('tasks', [task]) router.sendToUser(mo, userId)
def doBindInviteCode(self, gameId, userId, clientId, inviteCode): """绑定上线推荐人ID""" try: hall_simple_invite.bindSimpleInviteRelationShip(inviteCode, userId) mo = MsgPack() mo.setCmd('invite_info') mo.setResult('action', 'bind_invite_code') mo.setResult('code', 0) mo.setResult('state', 1) mo.setResult('gameId', gameId) # 绑定成功,获取推荐人信息 name, pic = self.getUserNameAndPic(inviteCode) mo.setResult('bindName', name) mo.setResult('bindPic', pic) mo.setResult('bindUserId', inviteCode) # 校验自己的领奖状态 timestamp = pktimestamp.getCurrentTimestamp() inviteeStatus = hall_simple_invite.loadStatus(userId, timestamp) mo.setResult('rewardState', inviteeStatus.getRewardState(userId, gameId, clientId)) 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.info('invite.statics eventId=', 'INPUT_INVITE_CODE', 'userId=', userId, 'clientId=', clientId, 'inviteCode=', inviteCode, 'result=', 'failed', 'ec=', ec, 'info=', info) router.sendToUser(self.makeErrorResponse('invite_info', 'bind_invite_code', ec, info), userId)
def getUpdateInfo(gameId, userId, clientId, version, updateVersion): global _updatesMap mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_game_update_info') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('clientId', clientId) updates = [] strGameId = str(gameId) if strGameId in _updatesMap: gUpdates = _updatesMap[strGameId] if version in gUpdates: vUpdates = gUpdates[version] for u in vUpdates: if updateVersion < int(u['updateVersion']): updates.append(u) if ftlog.is_debug(): ftlog.debug('hall_game_update.getUpdateInfo gameId:', gameId , ' userId:', userId , ' clientId:', clientId , ' version:', version , ' updateVersion:', updateVersion , ' updates:', updates ) mo.setResult('updates', updates) router.sendToUser(mo, userId) return updates
def buildFlipCardResponse(cls, gameId, userId, roomId, flipIndex, flippedCardList, benefitsSend, userBenefits): assert (flipIndex >= 0 and flipIndex <= len(flippedCardList)) flippedCard = flippedCardList[flipIndex] mo = MsgPack() mo.setCmd('flip_card_luck') mo.setResult('action', 'flip') mo.setResult('index', flipIndex) mo.setResult('userId', userId) mo.setResult('gameId', gameId) mo.setResult('cards', cls.encodeFlippedCardList(flippedCardList, flipIndex)) mo.setResult('desc', cls.getFlippedCardDesc(flippedCard)) if isinstance(flippedCard, FlippedCardProduct): payOrder = TodoTaskPayOrder(flippedCard.product) mo.setResult('sub_action', payOrder.toDict()) mo.setResult('sub_text', hallflipcardluck.getString('product.subText', '立即购买')) if benefitsSend: mo.setResult('sub_action_ext', TodoTaskHelper.makeTodoTaskBenefitsInfo(benefitsSend, userBenefits).toDict()) else: mo.setResult('sub_action_ext', TodoTaskNoop().toDict()) mo.setResult('sub_text_ext', hallflipcardluck.getString('product.subTextExt', '取消')) elif isinstance(flippedCard, FlippedCardAsset): if benefitsSend: mo.setResult('sub_action', TodoTaskHelper.makeTodoTaskBenefitsInfo(benefitsSend, userBenefits).toDict()) else: mo.setResult('sub_action', TodoTaskNoop().toStr()) mo.setResult('sub_text', hallflipcardluck.getString('item.subText', '确定')) 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 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 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 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 lostHandler(self, reason): if self.robotUser: mi = MsgPack() mi.setCmd('_tcp_closed_') self.robotUser.msgQueue.append(mi) else: pass
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 makeDataChangeNotifyMsg(gameId, userId, changedDataNames): msg = MsgPack() msg.setCmd('update_notify') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('changes', list(translateChangeDataNames(changedDataNames))) return msg
def do_get_task_reward(self, gameId, userId, clientId, taskid): curtime = pktimestamp.getCurrentTimestamp() task_kind = halltask._taskSystem.findTaskKind(taskid) if not task_kind: return subsys = task_kind.taskUnit.subTaskSystem if not isinstance(subsys, (HallNewUserSubTaskSystem, HallChargeSubTaskSystem)): # 目前只有这俩走这里 return try: taskmodel = subsys.loadTaskModel(userId, curtime, clientId) if not taskmodel: raise TYTaskException(-1, "未知的任务:%s" % taskid) task = taskmodel.userTaskUnit.findTask(taskid) if not task: raise TYTaskException(-2, "未知的任务:%s" % taskid) asset_list = subsys.getTaskReward(task, curtime, 'FREE_TASK', taskid) router.sendToUser(self._build_task_info(gameId, userId, clientId), userId) rewardstr = TYAssetUtils.buildContentsString(asset_list) mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_task_reward') mo.setResult('code', 0) mo.setResult('info', '恭喜您获得了%s' % rewardstr) router.sendToUser(mo, userId) except TYTaskException, e: mo = MsgPack() mo.setCmd('game') mo.setResult('action', 'get_task_reward') mo.setResult('code', e.errorCode) mo.setResult('info', e.message) router.sendToUser(mo, userId)
def sendNotifyMsg(cls, gameId, uid, showTime, content): """ { "cmd": "notifyMsg", "result": { "showTime": 0.5, "content": [{ "color": "RRGGBB", "text": "bababababa" }, { "color": "RRGGBB", "text": "bababababa" }] } } """ msg_content = [dict(zip(("color", "text"), segment)) for segment in content] message = MsgPack() message.setCmd('notifyMsg') message.setResult("userId", uid) message.setResult("gameId", gameId) message.setResult("showTime", showTime) message.setResult("content", msg_content) router.sendToUser(message, uid)
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 testQuickStart(self): '''测试快速开始''' gameId = 6 userId = random.randint(10000, 20000) roomId = 0 tableId = 0 chip = 800 clientId = "Android_3.501_tuyoo.YDJD.0-hall6.apphui.happy" playMode = "happy" onlinedata.setOnlineState(userId, onlinedata.ONLINE) onlinedata.cleanOnlineLoc(userId) userdata.setAttr(userId, "sessionClientId", clientId) # datas = sessiondata._getUserSessionValues(userId) # ftlog.debug("|userId, session:", userId, datas) oldChip = userchip.getChip(userId) userchip.incrChip(userId, gameId, chip - oldChip, 0, "GM_ADJUST_COIN", 0, clientId) msg = MsgPack() msg.setCmd("quick_start") msg.setParam("gameId", gameId) msg.setParam("userId", userId) # msg.setParam("roomId", roomId) # msg.setParam("tableId", tableId) msg.setParam("clientId", clientId) print '='*30 print msg BaseQuickStartDispatcher.dispatchQuickStart(msg, userId, gameId, roomId, tableId, playMode, clientId) print '='*30
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 enterFriendTable(self, userId, gameId, clientId, ftId): """进入自建桌,插件实现具体功能""" if ftlog.is_debug(): ftlog.debug('MAJIANG enterFriendTable userId:', userId , ' gameId:', gameId , ' clientId:', clientId , ' ftId:', ftId) tableId0, roomId0 = CreateTableData.getTableIdByCreateTableNo(ftId) if ftlog.is_debug(): ftlog.debug('MAJIANG enterFriendTable ftId:', ftId , ' roomId:', roomId0 , ' tableId:', tableId0) if not tableId0 or not roomId0: from difang.majiang2.entity.util import sendPopTipMsg sendPopTipMsg(userId, '您要进入的朋友场房间不存在,请核对房间号') return config = { "type": "game", "pluginParams": { "gameType": 11, "ftId": ftId } } todotask = TodoTaskEnterGameNew(GAMEID, config) mo = MsgPack() mo.setCmd('todo_tasks') mo.setResult('gameId', gameId) mo.setResult('pluginId', GAMEID) mo.setResult('userId', userId) mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask)) router.sendToUser(mo, userId)
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 makeErrorResponse(cls, cmd, action, errorCode, info): mo = MsgPack() mo.setCmd(cmd) mo.setResult('action', action) mo.setResult('code', errorCode) mo.setResult('info', info) mo.setResult('gameId', HALL_GAMEID) return mo
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 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 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 notifyMatchUserRevive(self, player, reviveContent): # 如果是机器人立即直接复活 if self.isRobot(player): self._room.match.currentInstance.doUserRevive(player, True) return afterScore = player.stage.stageConf.rankLine.getMinScoreByRank( reviveContent.get('rank')) afterRank = reviveContent.get('rank') # 判断用户是否需要高倍衰减 if player.championLimitFlag: rate = player.stage.nextStage.stageConf.scoreIntoRateHigh if player.stage.nextStage.stageConf.scoreIntoRateHigh else player.nextStage.stage.stageConf.scoreIntoRate afterScore = afterScore * rate else: afterScore = afterScore * player.stage.nextStage.stageConf.scoreIntoRate msg = MsgPack() msg.setCmd('m_revival') msg.setResult('mixId', player.mixId) msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('rank', player.rank) msg.setResult('afterRank', afterRank) msg.setResult('score', player.score) msg.setResult('afterScore', int(afterScore)) msg.setResult('riseUserCount', player.stage.stageConf.riseUserCount) msg.setResult( 'timeLeft', int(player.reviveExpirationTime - pktimestamp.getCurrentTimestamp())) fee = reviveContent['fee'] itemId = fee['itemId'] userAssets = hallitem.itemSystem.loadUserAssets(player.userId) timestamp = pktimestamp.getCurrentTimestamp() balance = userAssets.balance(HALL_GAMEID, itemId, timestamp) assetKind = hallitem.itemSystem.findAssetKind(itemId) msg.setResult( 'fee', { 'feeCount': fee['count'], 'leftFeeCount': balance, 'pic': fee.get('img') if fee.get('img') else assetKind.pic }) if ftlog.is_debug(): ftlog.debug('MatchPlayerNotifierDizhu.notifyMatchUserRevive', 'instId=', player.matchInst.instId, 'userId=', player.userId, 'signinParams=', player.signinParams, 'stageIndex=', player.stage.index, 'msg=', msg.pack(), 'rank=', player.rank) router.sendToUser(msg, player.userId)
def taskReady(self, *args): """ 任务准备 :param args: """ tasks = config.getNcmpttTaskConf(self.table.runConfig.fishPool) if len(tasks) == 0 or len(self.table.getBroadcastUids()) == 0: endTimer = FishTableTimer(self.table) endTimer.setup(0, "task_end", {"uid": 0, "task": self.taskName}) return self.taskId = "%d-%d" % (self.table.tableId, int(time.time())) for uid in self.table.getBroadcastUids(): if util.isFinishAllRedTask(uid): # 获得所有已完成的引导 self.userIds.append(uid) for uid in self.userIds: randTask = random.choice(tasks) task = copy.deepcopy(randTask) # player = self.table.getPlayer(uid) # 火炮装扮减少任务鱼数量(暂时不用) # if player: # if player.gunSkinId in self.wpFishNumScale.keys(): # fNumScale = self.wpFishNumScale.get(player.gunSkinId, 1) # for fId in task["targets"]: # fNum = task["targets"][fId]["fishNum"] # fNum = int(round(int(fNum) * fNumScale)) # fNum = fNum if fNum >= 1 else 1 # task["targets"][fId]["fishNum"] = fNum targets = task["targets"] readySeconds = task["readySeconds"] state = TaskState.TS_Ready # 任务即将开始 self.usersData[uid] = { "uid": uid, "task": task, "targets": targets, "state": state, "rewardType": 1, "results": {} } msg = MsgPack() msg.setCmd("ncmptt_task") msg.setResult("gameId", FISH_GAMEID) msg.setResult("userId", uid) msg.setResult("action", "ready") msg.setResult("taskId", task["taskId"]) msg.setResult("taskType", task["taskType"]) GameMsg.sendMsg(msg, uid) startTimer = FishTableTimer(self.table) self.userStartTimer[uid] = startTimer startTimer.setup(readySeconds, "task_start", { "uid": uid, "task": self.taskName })
def doSupCheckinMonth(gameId, userId, clientId): ftlog.debug('doSupCheckinMonth..userId', userId) try: mo = MsgPack() typeData, status = monthcheckin.supplementCheckin( userId, gameId, clientId) ftlog.debug('doCheckinMonth..supplementCheckin = ', status) mo.setCmd('month_checkin') if typeData == 1: mo.setResult('action', 'supCheckin') mo.setResult('lessCard', status['lessCard']) router.sendToUser(mo, userId) else: mo.setResult('action', 'supCheckin') 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') daysRewards.append({ 'days': rewardContent.get('days'), 'desc': reward.get('desc'), 'picUrl': reward.get('picUrl'), 'state': MonthCheckinHandler.calcDaysRewardState( status, rewardContent.get('days')) }) ftlog.debug( 'doUpdateMonthCheckin..days', rewardContent.get('days'), 'desc = ', reward.get('desc'), 'state = ', MonthCheckinHandler.calcDaysRewardState( status, rewardContent.get('days'))) mo.setResult('daysRewards', daysRewards) mo.setResult('descSucess', '恭喜你获得500金币+1幸运卡') router.sendToUser(mo, userId) except MonthCheckinException, e: mo = MsgPack() mo.setCmd('month_checkin') mo.setResult('action', 'supCheckin') mo.setError(e.errorCode, e.message) router.sendToUser(mo, userId) ftlog.warn('MonthCheckinException', e.errorCode, e.message)
def _sendBuyLevelGiftRet(userId, clientId, giftId, code, commonRewards): """ 发送购买礼包结果 """ message = MsgPack() message.setCmd("buyLevelGift") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) message.setResult("productId", giftId) message.setResult("code", code) if code == 0: message.setResult("commonRewards", commonRewards) router.sendToUser(message, userId) doSendLevelGift(userId, clientId)
def doTreasureChestAdd(self, userId, rewardType, rewardList, params): success = False if rewardType in [TREASURE_CHEST_TYPE_AS_WINSTREAK]: success = True dizhu_event_remote.publishTreasureChestEvent( DIZHU_GAMEID, userId, rewardType, rewardList, **params) mo = MsgPack() mo.setCmd('dizhu') mo.setResult('action', 'treasure_chest_add') mo.setResult('gameId', DIZHU_GAMEID) mo.setResult('userId', userId) mo.setResult('rewardList', rewardList) mo.setResult('success', success) return mo.pack()
def doGetCommonConfig(self, userId, gameId, clientId, configKey): ''' 获取透传给前端的通用配置 ''' config = hallconf.getCommonConfig(clientId, configKey) msg = MsgPack() msg.setCmd('game') msg.setResult('action', 'common_config') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('clientId', clientId) msg.setResult('configKey', configKey) msg.setResult('config', config) router.sendToUser(msg, userId)
def _notifyMatchWait(self, player, step=None): self.notifyMatchUpdate(player) self._notifyMatchRank(player) msg = MsgPack() msg.setCmd('m_wait') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('tableId', player.group.area.tableId) msg.setResult('mname', self._room.roomConf["name"]) msg.setResult('riseCount', player.group.stageConf.riseUserCount) if step != None: msg.setResult('step', 0) # 0 - 请稍后 1- 晋级等待 router.sendToUser(msg, player.userId)
def updateMsg(cls, msg=None, cmd=None, params=None, result=None, **other): if not msg: msg = MsgPack() if cmd: msg.setCmd(cmd) if params is not None: msg.setKey('params', params) if result is not None: msg.setKey('result', result) for k, v in other.items(): msg.setKey(k, v) return msg
def doGetAllMails(userId, mailSenderType): """ 发送收件箱邮件列表消息 """ if util.isFinishAllNewbieTask(userId): message = MsgPack() message.setCmd("fishMailList") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) message.setResult("mailTypeList", MAIL_SENDER_TYPE_LIST) message.setResult("mailType", mailSenderType) mails = getAllMail(userId).get(mailSenderType, []) message.setResult("mails", mails) router.sendToUser(message, userId)
def _doGainReward(cls, gameId, userId, clientId): mp = MsgPack() mp.setCmd('hall_rp_main') mp.setResult('action', 'gain_reward') mp.setResult('userId', userId) assetList = hall_red_packet_main.gainReward(userId, clientId) rewards = [{ 'itemId': atup[0].kindId, 'name': atup[0].displayName, 'url': atup[0].pic, 'count': atup[1] } for atup in assetList] if assetList else [] mp.setResult('rewards', rewards) return mp
def _queryMatchSignin(cls, userId, bigRoomId, mixId, clientId): ''' 报名比赛 ''' mo = MsgPack() mo.setCmd('m_signin') mo.setParam('gameId', DIZHU_GAMEID) mo.setParam('roomId', bigRoomId) mo.setParam('userId', userId) mo.setParam('clientId', clientId) dizhuVersion = SessionDizhuVersion.getVersionNumber(userId) mo.setParam('version', dizhuVersion) mo.setParam('feeIndex', 0) if mixId: mo.setParam('signinParams', {'mixId': mixId}) router.queryRoomServer(mo, bigRoomId) # ut向gr,相当于用户点报名传给gr
def _updateMatchTask(self, userId): """更新比赛任务""" player = self.getPlayer(userId) usersData = self._usersData.get(userId, {}) if player and usersData and usersData["results"]: msg = MsgPack() msg.setCmd("m_task") msg.setResult("gameId", FISH_GAMEID) msg.setResult("roomId", self.roomId) msg.setResult("tableId", self.tableId) msg.setResult("seatId", player.seatId) msg.setResult("userId", player.userId) msg.setResult("targets", usersData["results"]) GameMsg.sendMsg(msg, player.userId)
def makeDataChangeNotifyMsg(gameId, userId, changedDataNames): """ 生成发送的消息 :param gameId: 游戏ID :param userId: 玩家ID :param changedDataNames: :return: """ msg = MsgPack() msg.setCmd('update_notify') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('changes', list(translateChangeDataNames(changedDataNames))) return msg
def _sendLogOutMsg(protocol, errorCode, isabort): ''' 发送一个强制logout的消息后, 关闭用户的TCP的链接 ''' if errorCode != ERROR_SYS_LOGOUT_TIME_OUT: ml = MsgPack() ml.setCmd('logout') ml.setError( errorCode, pokerconf.getConnLogoutMsg(errorCode, 'Please try to login again')) protocol.writeEncodeMsg(ml.pack()) protocol.closeConnection(0) ftlog.info('_sendLogOutMsg address=', protocol.clientAddress, 'errorCode=', errorCode)
def doGetBonusInfo(userId): message = MsgPack() message.setCmd("fishStarGameInfo") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) message.setResult("code", 0) wishLuckyValue = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.wishLuckyValue) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.wishLuckyValue, wishLuckyValue) message.setResult("starBonusNum", wishLuckyValue) message.setResult("gameInfo", _getBonusGameInfo()) message.setResult("consumInfo", Bonus_Consum) router.sendToUser(message, userId)
def doMatchState(self, userId, gameId, roomId): msg = runcmd.getMsgPack() match_id = msg.getParam("match_id") if match_id: # 老比赛,由于前端新比赛也会发此消息,但没有match_id导致的问题,这里处理下 state = gdata.rooms()[roomId].getMatchState(userId, gameId, match_id) current_ts = int(time.time()) msg = MsgPack() msg.setCmd('match_state') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('state', state) msg.setResult('match_id', match_id) msg.setResult('current_ts', current_ts) router.sendToUser(msg, userId)
def notifyMatchCancelled(self, player, reason, info): ''' 通知用户比赛取消 ''' try: msg = MsgPack() msg.setCmd('m_over') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('reason', reason) msg.setResult('info', info) router.sendToUser(msg, player.userId) except: ftlog.error()
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) mo.setResult("matchType", "point") self.matchPlugin.getMatchInfo(self, userId, mo) router.sendToUser(mo, userId)
def _doView(cls, userId, gameId, clientId, videoId, timestmap=None): msg = MsgPack() msg.setCmd('dizhu') msg.setResult('action', 'replay_view') msg.setResult('gameId', gameId) msg.setResult('userId', userId) try: timestamp = timestmap or pktimestamp.getCurrentTimestamp() replay = replay_service.view(videoId, userId, timestamp) msg.setResult('video', {'views':replay.viewsCount, 'likes':replay.likesCount, 'url':''}) msg.setResult('videoUrl', replay_service.buildVideoDataUrl(videoId)) except TYBizException, e: msg.setResult('code', e.errorCode) msg.setResult('info', e.message)
def doGetMatchNotifyList(self, userId, gameId, clientId): ''' 获取赛事通知列表 ''' from hall.entity import hallnewnotify msg = MsgPack() msg.setCmd('hall') msg.setResult('action', 'getMatchNotifyList') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('matchNotifyList', hallnewnotify.getMatchNotifyList(userId)) router.sendToUser(msg, userId)
def _processActiveImpl(evt): actInstance = _getActInstance(evt.userId) if ftlog.is_debug(): ftlog.debug('_processActiveImpl userId=', evt.userId, 'gameId=', evt.gameId, 'type=', type(evt)) if actInstance and not actInstance.isExpired( pktimestamp.getCurrentTimestamp()): eventIds = [i.eventId for i in actInstance.activeEvent] if isinstance(evt, HallShare3Event): eventId = evt.sharePointId elif isinstance(evt, ActiveEvent): eventId = evt.eventId elif isinstance(evt, ChargeNotifyEvent): eventId = 'recharge' elif isinstance(evt, TYOrderDeliveryEvent): eventId = 'exchangeCoin' else: return if ftlog.is_debug(): ftlog.debug('_processActiveImpl userId=', evt.userId, 'gameId=', evt.gameId, 'eventId=', eventId, 'eventIds=', eventIds) if str(eventId) in eventIds: actValue = 0 for act in actInstance.activeEvent: if act.eventId == str(eventId): actValue = act.active break if ftlog.is_debug(): ftlog.debug('_processActiveImpl userId=', evt.userId, 'gameId=', evt.gameId, 'actValue=', actValue) if actValue: # 完成活跃分享任务记录每日完成状态,增加日、周活跃值 userData, _, _ = UserActiveData(evt.userId).loadData() if str(eventId) in userData.activeDataDay.eventIdList: return userData.activeDataDay.eventIdList.append(str(eventId)) userData.addDayWeekActive(actValue) clientId = sessiondata.getClientId(evt.userId) activityWxList = ActivityWxHelper.getActivityList( evt.userId, clientId) mo = MsgPack() mo.setCmd('act_wx') mo.setResult('action', 'list') mo.setResult('gameId', DIZHU_GAMEID) mo.setResult('userId', evt.userId) mo.setResult('list', activityWxList) router.sendToUser(mo, evt.userId) if ftlog.is_debug(): ftlog.debug('_processShareActiveImpl userId= ', evt.userId, 'gameId= ', evt.gameId, 'eventId= ', eventId)
def _doGetProduct(cls, gameId, userId, clientId, shelvesName, timestamp): mo = MsgPack() mo.setCmd('store_exchange') mo.setResult('action', 'get_product') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('shelvesName', shelvesName) shelves = hall_exmall.getShelvesByName(userId, clientId, shelvesName, timestamp) exchangeIds = shelves.get('products', []) if shelves else [] exchanges = cls.encodeExchanges(gameId, userId, clientId, exchangeIds, timestamp) mo.setResult('list', exchanges) return mo
def doSignout(self, userId): ftlog.debug("<<", "|userId, roomId:", userId, self.roomId, caller=self) mo = MsgPack() mo.setCmd('m_signout') mo.setResult('gameId', self.gameId) mo.setResult('roomId', self.bigRoomId) mo.setResult('userId', userId) try: if self.match.signout(userId): self.reportBiGameEvent("MATCH_SIGN_OUT", userId, self.roomId, 0, 0, 0, 0, 0, [], 'match_signout') except MatchException, e: self.matchPlugin.handleMatchException(self, e, userId, mo)
def _dealTing(self, msg): message = MsgPack() message.setCmd("table_call") message.setParam("action", "ting") message.setParam('userId', self.userId) message.setParam('gameId', self.gameId) message.setParam('clientId', self.clientId) message.setParam('roomId', self.roomId) message.setParam('tableId', self.tableId) message.setParam('seatId', self.seatId) message.setParam('ting_info', []) message.setParam('server_reply', 1) message.setParam('action_id', msg.getResult("action_id")) self.writeMsg(message)
def _updateMatchRank(self, userId): """比赛排名""" player = self.getPlayer(userId) if player and player.userId and self._match_table_info: msg = MsgPack() msg.setCmd("m_update") msg.setResult("gameId", FISH_GAMEID) msg.setResult("roomId", self.roomId) msg.setResult("tableId", self.tableId) msg.setResult("seatId", player.seatId) msg.setResult("userId", player.userId) msg.setResult("rank", [player.rank, self._match_table_info["playerCount"]]) GameMsg.sendMsg(msg, player.userId)
def _doListMine(cls, userId, gameId, clientId): msg = MsgPack() msg.setCmd('dizhu') msg.setResult('action', 'replay_mine_list') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('shareMsg', replay_service.getShareDesc(userId, gameId, clientId)) timestamp = pktimestamp.getCurrentTimestamp() lastView = replay_service.getLastView(userId) replays = replay_service.getMine(userId, timestamp) msg.setResult('videos', cls.encodeReplaysForMine(userId, replays, lastView)) router.sendToUser(msg, userId) replay_service.setLastView(userId, timestamp) return msg
def _dealWin(self, msg): tile = msg.getResult("tile") message = MsgPack() message.setCmd("table_call") message.setParam("action", "win") message.setParam("tile", tile) message.setParam('userId', self.userId) message.setParam('gameId', self.gameId) message.setParam('clientId', self.clientId) message.setParam('roomId', self.roomId) message.setParam('tableId', self.tableId) message.setParam('seatId', self.seatId) message.setParam('action_id', msg.getResult("action_id")) self.writeMsg(message)
def doGetAchievelLevelInfos(userId): """获取成就等级信息""" achLevelClass = AchievementLevel(userId) message = MsgPack() message.setCmd("achievement_level_info") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) if isLimitLevel(userId): message.setResult("code", 7) router.sendToUser(message, userId) return message.setResult("code", 0) message.setResult("levelInfos", achLevelClass.getAllLevelInfos()) router.sendToUser(message, userId)
def notifyQuickGotoDizhuMatch(cls, gameId, userId, roomId, **kwargs): mixId = kwargs.get('mixId', '') if ftlog.is_debug(): ftlog.debug("DizhuQuickStart.onCmdQuickStart.notifyQuickGotoDizhuMatch:notify|", "userId=", userId, "gameId=", gameId, "roomId=", roomId, "mixId=", mixId) mo = MsgPack() mo.setCmd('quick_start') mo.setResult('gameId', gameId) mo.setResult('userId', userId) mo.setResult('roomId', roomId) mo.setResult('seatId', 0) mo.setResult('isOK', True) mo.setResult('mixId', mixId) mo.setResult('isMatch', 1) router.sendToUser(mo, userId)