NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

mockMessenger.py (10383B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\packages\dailygoals\client\mockMessenger.py
      2 from six.moves import http_client as httplib
      3 import logging
      4 import uuid
      5 import datetime
      6 import blue
      7 from carbon.common.script.sys.serviceConst import ROLE_QA, ROLE_PROGRAMMER
      8 from dailygoals.client.utils import format_goal_from_payload
      9 import dailygoals.client.qa_settings as daily_goals_qa_settings
     10 from dailygoals.client.const import DailyGoalCategory
     11 from eveProto.generated.eve_public.dailygoal.api.requests_pb2 import GetRequest, GetResponse, GetAllCurrentRequest, GetAllCurrentResponse, GetAllWithRewardsRequest, GetAllWithRewardsResponse, RedeemRequest, RedeemResponse
     12 from eveProto.generated.eve_public.dailygoal.api.admin.admin_pb2 import ProgressRequest, ProgressResponse
     13 from eveProto.generated.eve_public.dailygoal.api.notices_pb2 import ProgressedNotice, CompletedNotice, CurrentGoalsNotice, RedeemedNotice
     14 import dailygoals.client.goalMessengerSignals as messenger_signals
     15 from dailygoals.client.errors import GoalMessengerError, GoalNotRedeemableToCurrentLocation
     16 from dailygoals.client.const import RewardType, DailyGoalCategory
     17 logger = logging.getLogger(__name__)
     18 MONTHLY_GOAL_TEMPLATE = {'contribution_fields': {'daily_goal': None,
     19                          'daily_goal_category': 2},
     20  'assigner_id': 1000413,
     21  'progress': 3,
     22  'career_id': None,
     23  'contribution_method_id': 'CompleteGoal',
     24  'category': DailyGoalCategory.CATEGORY_MONTHLY_BONUS,
     25  'active_after': None,
     26  'target': None,
     27  'desc_id': 699209,
     28  'has_earnings': False,
     29  'help_text_id': 699210,
     30  'goal_id': None,
     31  'name_id': 699211,
     32  'active_until': None,
     33  'omega': False}
     34 
     35 def _create_base_monthly_goal():
     36     goal = MONTHLY_GOAL_TEMPLATE.copy()
     37     goal['active_after'] = datetime.datetime.now()
     38     goal['active_until'] = datetime.datetime.now() + datetime.timedelta(1)
     39     return goal
     40 
     41 
     42 def get_mock_monthly_goals():
     43     goals_dict = {}
     44     for num in range(1, 5):
     45         key = 'monthly_goal_{}'.format(num)
     46         goals_dict[key] = _create_base_monthly_goal()
     47         goals_dict[key]['target'] = 3 * num
     48         goals_dict[key]['is_omega'] = False
     49         goals_dict[key]['goal_id'] = uuid.uuid4()
     50         key = 'monthly_omega_goal_{}'.format(num)
     51         goals_dict[key] = _create_base_monthly_goal()
     52         goals_dict[key]['target'] = 3 * num
     53         goals_dict[key]['is_omega'] = True
     54         goals_dict[key]['goal_id'] = uuid.uuid4()
     55 
     56     goals_dict['monthly_goal_1']['rewards'] = [{'reward_type': RewardType.LOYALTY_POINTS,
     57       'amount': 5000}]
     58     goals_dict['monthly_goal_1']['has_earnings'] = True
     59     goals_dict['monthly_omega_goal_1']['rewards'] = [{'reward_type': RewardType.LOYALTY_POINTS,
     60       'amount': 10000,
     61       'is_omega_restricted': True}]
     62     goals_dict['monthly_omega_goal_1']['has_earnings'] = True
     63     goals_dict['monthly_goal_2']['rewards'] = [{'reward_type': RewardType.ITEM,
     64       'amount': 1,
     65       'item_type_id': 83679}]
     66     goals_dict['monthly_omega_goal_2']['rewards'] = [{'reward_type': RewardType.ITEM,
     67       'amount': 1,
     68       'item_type_id': 83639}]
     69     goals_dict['monthly_goal_3']['rewards'] = [{'reward_type': RewardType.ISK,
     70       'amount': 8000000}]
     71     goals_dict['monthly_omega_goal_3']['rewards'] = [{'reward_type': RewardType.PLEX,
     72       'amount': 5}]
     73     goals_dict['monthly_goal_4']['rewards'] = [{'reward_type': RewardType.SKILL_POINTS,
     74       'amount': 25000}]
     75     goals_dict['monthly_omega_goal_4']['rewards'] = [{'reward_type': RewardType.SKILL_POINTS,
     76       'amount': 150000}]
     77     return goals_dict
     78 
     79 
     80 class MockDailyGoalMessenger(object):
     81     _instance = None
     82     public_gateway = None
     83 
     84     @classmethod
     85     def get_instance(cls, public_gateway):
     86         if not cls._instance:
     87             cls._instance = MockDailyGoalMessenger(public_gateway)
     88         return cls._instance
     89 
     90     def __init__(self, public_gateway):
     91         self.public_gateway = public_gateway
     92         self.mock_goal_dict = None
     93         self.mock_id_list = None
     94         self._subscribe_to_notices()
     95 
     96     def _subscribe_to_notices(self):
     97         self.public_gateway.subscribe_to_notice(CurrentGoalsNotice, lambda payload, _: self.on_current_goals_received(payload))
     98         self.public_gateway.subscribe_to_notice(CompletedNotice, lambda payload, _: self.on_goal_completed(payload))
     99         self.public_gateway.subscribe_to_notice(ProgressedNotice, lambda payload, _: self.on_goal_progressed(payload))
    100         self.public_gateway.subscribe_to_notice(RedeemedNotice, lambda payload, _: self.on_goal_redeemed(payload))
    101 
    102     def _is_programmer(self):
    103         return session and session.role & ROLE_PROGRAMMER
    104 
    105     def get_mock_monthly_list(self):
    106         if self.mock_goal_dict is None:
    107             self.mock_goal_dict = get_mock_monthly_goals()
    108             self.mock_id_list = [ goal['goal_id'] for goal in self.mock_goal_dict.itervalues() ]
    109         return [ goal for goal in self.mock_goal_dict.itervalues() ]
    110 
    111     def get_mock_goal_ids(self):
    112         goal_list = self.get_mock_monthly_list()
    113         return [ goal['goal_id'] for goal in goal_list ]
    114 
    115     def get_mock_goal(self, goal_id):
    116         for goal in self.get_mock_monthly_list():
    117             if goal['goal_id'] == goal_id:
    118                 return goal
    119 
    120     def iter_format_goals(self, goals):
    121         for goal in goals:
    122             yield format_goal_from_payload(goal_id=uuid.UUID(bytes=goal.id.uuid), goal_attributes=goal.goal, goal_progress=goal.current_progress, earnings=goal.earnings)
    123 
    124     def get_current_goals(self):
    125         if self._is_programmer():
    126             if daily_goals_qa_settings.daily_goals_get_goals_force_delay.get() > 0:
    127                 blue.synchro.Sleep(daily_goals_qa_settings.daily_goals_get_goals_force_delay.get() * 1000)
    128             if daily_goals_qa_settings.daily_goals_get_goals_force_errors.get():
    129                 if daily_goals_qa_settings.daily_goals_get_goals_randomize_errors.get():
    130                     import random
    131                     if random.random() > 0.5:
    132                         raise Exception
    133                 else:
    134                     raise Exception
    135         logger.info('Daily Goals: sending GetAllCurrentRequest')
    136         request = GetAllCurrentRequest()
    137         payload = self._send_request(request, GetAllCurrentResponse)
    138         data = [ goal for goal in self.iter_format_goals(payload.goals) if goal['category'] != DailyGoalCategory.CATEGORY_MONTHLY_BONUS ]
    139         for goal in data:
    140             goal['omega'] = False
    141 
    142         data.extend(self.get_mock_monthly_list())
    143         return data
    144 
    145     def get_goal(self, goal_id):
    146         logger.info(u'Daily Goals: sending GetRequest for goal %s' % goal_id)
    147         if goal_id in self.get_mock_goal_ids():
    148             mock_goal = self.get_mock_goal(goal_id)
    149             return mock_goal
    150         request = GetRequest()
    151         request.goal.uuid = goal_id.bytes
    152         payload = self._send_request(request, GetResponse)
    153         goal_data = format_goal_from_payload(goal_id=goal_id, goal_attributes=payload.goal, goal_progress=payload.progress, earnings=payload.earnings)
    154         return goal_data
    155 
    156     def get_all_with_rewards_page(self, token = '', size = 100):
    157         logger.info('Daily Goals: sending GetAllWithRewardsRequest')
    158         request = GetAllWithRewardsRequest()
    159         request.page.size = size
    160         request.page.token = token
    161         try:
    162             logger.info('GetAllWithRewardsRequest sent with data %s', request)
    163             payload = self._send_request(request, GetAllWithRewardsResponse)
    164             logger.info('GetAllWithRewardsResponse received with data %s', payload)
    165         except GoalMessengerError as gme:
    166             logger.error('Daily Goals: Unable to get page with token %s' % token)
    167             raise gme
    168 
    169         goal_id_list = [ uuid.UUID(bytes=identifier.uuid) for identifier in payload.ids ]
    170         goal_id_list.extend(self.get_mock_goal_ids())
    171         return (payload.next_page.token, goal_id_list)
    172 
    173     def redeem_reward(self, goal_id, do_redeem_current_location):
    174         logger.info('Daily Goals: sending RedeemRequest for goal %s' % goal_id)
    175         request = RedeemRequest()
    176         request.goal.uuid = goal_id.bytes
    177         request.redeem_current_location = do_redeem_current_location
    178         try:
    179             self._send_request(request, RedeemResponse)
    180         except GoalMessengerError as gme:
    181             logger.error('Daily Goals: error while redeeming reward for goal %s' % goal_id)
    182             if do_redeem_current_location and gme.status_code == httplib.FORBIDDEN:
    183                 raise GoalNotRedeemableToCurrentLocation(goal_id, session.locationid)
    184 
    185     def set_goal_progress(self, goal_id, character_id, progress_to_add):
    186         logger.info('Daily Goals: sending ProgressRequest for goal %s, progress +=%s' % (goal_id, progress_to_add))
    187         if session and session.role & ROLE_QA:
    188             request = ProgressRequest()
    189             request.goal.uuid = goal_id.bytes
    190             request.character.sequential = character_id
    191             request.progress = progress_to_add
    192             self._send_request(request, ProgressResponse)
    193 
    194     def on_current_goals_received(self, _payload):
    195         messenger_signals.on_current_goals_received_internal()
    196 
    197     def on_goal_completed(self, payload):
    198         logger.info('Daily Goals: goal %s Completed Notice' % payload.goal)
    199         goal_id = uuid.UUID(bytes=payload.goal.uuid)
    200         messenger_signals.on_goal_completed_internal(goal_id)
    201 
    202     def on_goal_progressed(self, payload):
    203         goal_id = uuid.UUID(bytes=payload.goal.uuid)
    204         current_progress = payload.current_progress
    205         messenger_signals.on_goal_progressed_internal(goal_id, current_progress)
    206 
    207     def on_goal_redeemed(self, payload):
    208         goal_id = uuid.UUID(bytes=payload.goal.uuid)
    209         messenger_signals.on_goal_redeemed_internal(goal_id)
    210 
    211     def _send_request(self, request, response_class):
    212         request_primitive, response_channel = self.public_gateway.send_character_request(request, response_class)
    213         response_primitive, payload = response_channel.receive()
    214         if response_primitive.status_code != httplib.OK:
    215             logger.error('%s returned with statusCode %s, statusMessage: %s', request.DESCRIPTOR.full_name, response_primitive.status_code, response_primitive.status_message)
    216             raise GoalMessengerError(request.DESCRIPTOR.name, response_primitive.status_code)
    217         return payload