def path_find(self, x, y):
        """
        "A-star" is probably a cloth brand from some US rap singer...
        Let's do our own stupid greedy, short-sighted algo instead, right?
        """
        if self.x == x and self.y == y:
            return Action(ActionType.STOP)

        direction = None
        if self.y > y:
            if not self.blocked(self.x, self.y - 1):
                direction = Direction.NORTH
        elif self.y < y:
            if not self.blocked(self.x, self.y + 1):
                direction = Direction.SOUTH
        if direction is None and self.x > x:
            if not self.blocked(self.x - 1, self.y):
                direction = Direction.WEST
        elif direction is None and self.x < x:
            if not self.blocked(self.x + 1, self.y):
                direction = Direction.EAST

        if direction is not None:
            return Action(ActionType.MOVE, direction)
        else:
            self.random_steps = 10
            self.random_action = RandomPolicy().action(self.team_id,
                                                       self.observation)
            return self.random_action
Exemple #2
0
def work():
    if not client_status.is_actual_version():
        check_update()

    actions.clear()
    if client_status.last_fs_upload:
        nxt = client_status.last_fs_upload + timedelta(seconds=FS_SET_PERIOD)
        till_next = max(0, total_seconds(nxt - datetime.utcnow()))
        del nxt
    else:
        till_next = 0
    actions.add(Action(24 * HOUR, check_system_info, start=2 * MIN))
    actions.add(StepAction(FS_SET_PERIOD, update_fs, start=till_next))
    actions.extend([
        Action(LOG_UPLOAD_PERIOD, upload_log),
        Action(CHANGES_CHECK_PERIOD, check_changes)
    ])

    if config.database or client_status.database:
        actions.add(Action(DB_CHECK_PERIOD, check_db, start=7 * MIN))

    if client_status.amazon:
        actions.add(Action(backup.next_date, make_backup))
    else:
        actions.add(
            OneTimeAction(
                5 * MIN,
                get_s3_access,
                followers=[ActionSeed(backup.next_date, make_backup)]))

    if os.path.exists(CRASH_PATH) and os.stat(CRASH_PATH).st_size > 0:
        actions.add(OneTimeAction(10 * MIN, report_crash, start=0))

    try:
        log.info('Action pool is:\n%s' % '\n'.join([str(a) for a in actions]))
    except TypeError:
        msg = ['Failed to iterate actions.']
        if isinstance(actions, ActionPool):
            msg.append('ActionPool object has %s__iter__ method.')
            msg[-1] %= '' if hasattr(actions, '__iter__') else 'no '
            if hasattr(actions, '_actions'):
                if isinstance(actions._actions, list):
                    if actions._actions:
                        f = ', '.join((a.__name__ for a in actions._funcs()))
                        msg.append('There are functions: %s.' % f)
                    else:
                        msg.append('_actions is empty list.')
                else:
                    msg.append('_actions is %s.' % type(actions._actions))
            else:
                msg.append('There is no _actions in actions.')
        else:
            msg.append('Type of actions is %s' % type(actions))
        log.error(' '.join(msg))
    log.info('Start main loop')
    while True:
        action = actions.next()
        log.info('Next action is %s' % action)
        time.sleep(action.time_left())
        action()
Exemple #3
0
    def __init__(self):
        self.isEnabled = True
        self.openInven = Action(0, self.openInventory)
        self.feedBeer = Action(0, self.feedBeerToWorkers)

        self.last_frame = None
        self.state = State.BASE
    def update(self, agent_update):
        observation_map = agent_update.observation_map
        observation = observation_map.observations[self.agent_id]
        self.position = (
            observation.get_value(self.feature_names['x']).feature_value,
            observation.get_value(self.feature_names['y']).feature_value,
            )

        observed_bases = {}
        for direction, basis in zip(self.direction_bases.keys(), self.direction_bases.values()):
            distance = observation.get_value(self.feature_names[direction]).feature_value
            observed_bases[basis] = distance
        """
        if self.updates < 5:
            print "agent position: " + str(self.position)
            print "bases: " + str(observed_bases)
            self.updates += 1
            """

        self.log_map, self.observed_map = self.update_maps(
            self.position,
            self.log_map,
            self.observed_map,
            observed_bases,
            )

        action_map = ActionMap()
        action = Action()
        next_x, next_y = self.next_movement(self.position, self.log_map)
        x_component = NumericActionComponent(next_x)
        action.add_component(self.component_names['x'], x_component)
        y_component = NumericActionComponent(next_y)
        action.add_component(self.component_names['y'], y_component)
        action_map.add_action(self.agent_id, action)
        return action_map
Exemple #5
0
 def __init__(self, log, conf=None):
     Action.__init__(self, log, conf)
     self.log = log
     self.records = []
     self.sources = {}
     self.debug_records_sent = []
     if conf:
         for c in conf:
             self.add_source(c)
Exemple #6
0
def new_message():
    message_complete_data = json.loads(request.data)
    print(message_complete_data)
    try:
        action = Action(bot_name, telegram_uri, message_complete_data)
        action.evaluate()
        return 'Action has been executed'
    except:
        return 'Error excecuting action'
Exemple #7
0
def handle_keys_choose_option(key):
    action: [Action, None] = None

    index = key - 97
    if index >= 0:
        return Action(ActionType.CHOOSE_OPTION, option_index=index)

    elif key == tcod.event.K_TAB or key == tcod.event.K_ESCAPE:
        return Action(ActionType.TOGGLE_INVENTORY)
    return action
Exemple #8
0
def handle_keys_main_menu(key):
    action: [Action, None] = None

    if key == tcod.event.K_a:
        action = Action(ActionType.NEW_GAME)
    elif key == tcod.event.K_b:
        action = Action(ActionType.LOAD_GAME)
    elif key in (tcod.event.K_c, tcod.event.K_ESCAPE):
        action = Action(ActionType.ESCAPE)

    return action
Exemple #9
0
def handle_keys_targeting(key):
    action: [Action, None] = None

    action = handle_movement_keys(key)

    if action is None:
        if key == tcod.event.K_ESCAPE:
            action = Action(ActionType.ESCAPE)
        elif key in (tcod.event.K_KP_ENTER, tcod.event.K_SPACE):
            action = Action(ActionType.EXECUTE)

    return action
Exemple #10
0
def handle_keys_player_turn(key) -> [Action, None]:
    action: [Action, None] = None

    if key == tcod.event.K_g:
        action = Action(ActionType.GRAB)

    elif key == tcod.event.K_a:
        action = Action(ActionType.TOGGLE_INVENTORY)

    elif key == tcod.event.K_d:
        action = Action(ActionType.DROP_INVENTORY_ITEM)

    elif key == tcod.event.K_PERIOD:
        action = Action(ActionType.WAIT)

    elif key == tcod.event.K_SPACE:
        action = Action(ActionType.INTERACT)

    elif key == tcod.event.K_e:
        action = Action(ActionType.LOOK)

    elif key == tcod.event.K_ESCAPE:
        action = Action(ActionType.ESCAPE)

    elif key == tcod.event.K_r:
        action = Action(ActionType.SWAP_APPENDAGE)

    elif action is None:
        action = handle_movement_keys(key)

    # No valid key was pressed
    return action
Exemple #11
0
 def __init__(self, rule_context, rule_state, data, nested_rule):
     """
     @type rule_state: RuleState
     @type rule_context: RuleContext
     @type data: matplotlib.pyparsing.ParseResults
     @type nested_rule: Rule
     @type parent_rule: Rule
     """
     self.nested_rule = nested_rule
     self.parent = None
     if self.nested_rule is None:
         self.actions = [
             Action(action, 'always_fire_actions' in data)
             for action in data['actions']
         ]
     else:
         self.actions = []
         self.nested_rule.set_parent(self)
     self.override = "override" in data
     self.overrideOff = False
     if self.override and len(data["override"]) == 1:
         warning = "rule '%s' has override configuration and will turn a possible override state off"
         self.overrideOff = True
         __logger__.info(warning % rule_state.rule_name)
     elif self.override:
         __logger__.info(
             "rule '%s' has override configuration and will turn a possible override state on"
             % rule_state.rule_name)
     self.rule_state = rule_state
     self.rule_context = rule_context
     self.always_fire = False
Exemple #12
0
 def load_actions(self, table, table_name):
     built_actions = {}
     for item in table.all():
         new_object = Action.get_action(self, table, item.eid, item,
                                        table_name)
         built_actions[item.eid] = new_object
     return built_actions
 def __init__(self, **enemy):
     self.name = enemy['name']
     self.size = enemy['size']
     self.type = enemy['type']
     self.alignment = enemy['alignment']
     self.AC = enemy['ac']
     self.armorType = enemy['armorType']
     self.hp = enemy['hp']
     self.STR = enemy['STR']
     self.DEX = enemy['DEX']
     self.CON = enemy['CON']
     self.INT = enemy['INT']
     self.WIS = enemy['WIS']
     self.CHA = enemy['CHA']
     self.initiative = enemy['initiative']
     self.alive = True
     self.currentstatus = 'Healthy'
     self.actions = [Action(**i) for i in enemy['actions']]
     self.max = enemy['maxhp']
     self.enemyId = enemy['enemyId']
     self.combatId = enemy['combatId']
     self.savingThrows = enemy.get('savingThrows', None)
     self.challenge = enemy['challenge']
     self.languages = enemy['languages']
     self.senses = enemy['senses']
     self.bloodied = enemy['bloodied']
     self.damage_vulnerabilities = enemy['damage_vulnerabilities']
     self.damage_resistances = enemy['damage_resistances']
     self.damage_immunities = enemy['damage_immunities']
     self.condition_immunities = enemy['condition_immunities']
     if enemy.get('specialTraits', None):
         self.specialTraits = [
             SpecialTraits(**i) for i in enemy['specialTraits']
         ]
     self.actionsText = [ActionsText(**i) for i in enemy['actionsText']]
Exemple #14
0
def main():

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--credentials', type=existing_file,
                        metavar='OAUTH2_CREDENTIALS_FILE',
                        default=os.path.join(
                            os.path.expanduser('/home/pi/.config'),
                            'google-oauthlib-tool',
                            'credentials.json'
                        ),
                        help='Path to store and read OAuth2 credentials')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))

    with Assistant(credentials) as assistant:
        subprocess.Popen(["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        for event in assistant.start():
            process_event(event)
            usrcmd=event.args
            if 'trigger'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                Action(str(usrcmd).lower())
            if 'play'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                YouTube(str(usrcmd).lower())
            if 'stop'.lower() in str(usrcmd).lower():
                stop()
def handle_keys(key) -> [Action, None]:
    action: [Action, None] = None

    if key == tcod.event.K_UP:
        action = Action(ActionType.MOVEMENT, dx=0, dy=-1)
    elif key == tcod.event.K_DOWN:
        action = Action(ActionType.MOVEMENT, dx=0, dy=1)
    elif key == tcod.event.K_LEFT:
        action = Action(ActionType.MOVEMENT, dx=-1, dy=0)
    elif key == tcod.event.K_RIGHT:
        action = Action(ActionType.MOVEMENT, dx=1, dy=0)

    elif key == tcod.event.K_ESCAPE:
        action = Action(ActionType.ESCAPE)

    # No valid key was pressed
    return action
Exemple #16
0
def set_context(received_context):
    global context
    context = received_context
    context.register_action(
        Action("screenshot",
               take_screenshot,
               menu_name="Take screenshot",
               description="Takes a screenshot from previous app"))
Exemple #17
0
 def add_action(self, textMessage):
     cmd = extract_verb(textMessage.lower())
     print(cmd)
     args = textMessage.replace(cmd, '')
     runner = None
     if cmd == "fala":
         runner = TalkRunner()
     action = Action(runner, args)
     self.actions.append(action)
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--credentials', type=existing_file,
                        metavar='OAUTH2_CREDENTIALS_FILE',
                        default=os.path.join(
                            os.path.expanduser('~/.config'),
                            'google-oauthlib-tool',
                            'credentials.json'
                        ),
                        help='Path to store and read OAuth2 credentials')
    parser.add_argument('--device_model_id', type=str,
                        metavar='DEVICE_MODEL_ID', required=True,
                        help='The device model ID registered with Google.')
    parser.add_argument('--project_id', type=str,
                        metavar='PROJECT_ID', required=False,
                        help='The project ID used to register device '
                        + 'instances.')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))
    with Assistant(credentials, args.device_model_id) as assistant:
        subprocess.Popen(["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        events = assistant.start()
        print('device_model_id:', args.device_model_id + '\n' +
              'device_id:', assistant.device_id + '\n')
        if args.project_id:
            register_device(args.project_id, credentials,
                            args.device_model_id, assistant.device_id)
        for event in events:
            process_event(event, assistant.device_id)
            usrcmd=event.args
            
            if 'trigger'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                Action(str(usrcmd).lower())
            if 'stream'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                YouTube(str(usrcmd).lower())
            if 'stop'.lower() in str(usrcmd).lower():
                stop()
            if 'tune into'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                radio(str(usrcmd).lower())
            if 'wireless'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ESP(str(usrcmd).lower())
            if 'parcel'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                track()
            if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                feed(str(usrcmd).lower())
            if 'on kodi'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kodiactions(str(usrcmd).lower())
Exemple #19
0
 def _valid_actions(self):
     valid_actions = []
     for act in Action.__members__.values():
         lines = self._get_lines(action=act.get_value())
         if self._game_board.movable(lines=lines,
                                     to_left=Action.left_direction(
                                         act.get_value())):
             valid_actions.append(act.get_value())
     return valid_actions
Exemple #20
0
 def get_stacked_action(self, stacked_state):
     """Given the current (stacked) game state, determine what action the model will output"""
     # take a random action epsilon fraction of the time
     if random.random() < self.epsilon:
         return get_random_action()
     # otherwise, take the action which maximizes expected reward
     else:
         q_values = self.net(
             torch.FloatTensor(stacked_state).to(self.device))
         action_idx = torch.argmax(q_values).item()
         return Action(action_idx)
Exemple #21
0
    def do_action(self, action: actions.Action,
                  pos: base.Vec2d) -> actions.Action:
        if self.modules[pos.x][pos.y].active:
            self.active_modules.remove((pos.x, pos.y))

        self.modules[pos.x][pos.y] = action.do(self.modules[pos.x][pos.y], pos)

        if self.modules[pos.x][pos.y].active:
            self.active_modules.add((pos.x, pos.y))

        return action
Exemple #22
0
 def play_guard(self, player: int, target: int, guess: Cards) -> Action:
     print('player: {0}, target: {1}, guess: {2}'.format(
         player, target, guess))
     if (target == -1):
         raise IllegalActionException('Target myst be specified')
     if (player == target):
         raise IllegalActionException('Player cannot target themself')
     if (guess == None):
         raise IllegalActionException('Player must guess a card')
     if (guess == Cards.GUARD):
         raise IllegalActionException('Player cannot guess a guard')
     return Action(Cards.GUARD, player, target, guess)
Exemple #23
0
 def __init__(self, type_):
     f = open(os.path.join("data/enemy_data.json"), "r")
     data = json.load(f)
     if type_ not in data.keys():
         raise Exception("Sorry, no enemies availible")
     self.enemy = data[type_]
     self.type = type_
     self.actions = []
     #Damage list of two ints, damage will RANGE from the first & second. EX. CSE220 dmg ranges from 5 to 12
     self.damage = self.enemy["damage"]
     self.hp = 100
     for action in self.enemy["actions"]:
         self.actions.append(Action(action))
Exemple #24
0
 def get_action(self, state):
     """Used when playing the actual game"""
     if random.random() < self.end_epsilon:
         return get_random_action()
     else:
         pp_state = self.preprocess_state(state)
         self.state_buffer.append(pp_state)
         stacked_state = np.stack([self.state_buffer])
         q_vals = self.net(
             torch.FloatTensor(stacked_state).to(self.device)).to(
                 self.device)
         action_idx = torch.argmax(q_vals).item()
         return Action(action_idx)
Exemple #25
0
    def __init__(self):
        self.isEnabled = False

        self.reelInFishAction = Action(0, self.reelInFish)
        self.castLineAction = Action(0, self.castLine)
        self.classifier = Classifier('./ml/')
        self.comp_img = cv.imread('resources/fishing_space_bar.jpg', 0)
        self.window = GameWindow("BLACK DESERT")
        self.colorGrabber = ColorGrabber()

        self.outputColors = False
        self.outputKeys = False
        self.swapRods = False
        self.rodCharSeq = ''
        self.rodSwapThresh = 5

        self.collectAll = True
        self.discardBlue = False
        self.discardGreen = False
        self.collectUnknowns = False

        self.reset()
Exemple #26
0
 def deserialize(cls, state, logger):
     game = cls(logger)
     game.game_id = state['id']
     game.num_players = state['numPlayers']
     for player in state['players']:
         game.players.append(Player.deserialize(player, logger))
     for action in state['actions']:
         game.actions.append(Action.deserialize(action, logger))
     game.harvests = state['harvests']
     game.turn = state['turn']
     game.starting_player_idx = state['startingPlayerIdx']
     game.active_player_idx = state['activePlayerIdx']
     game.phase = state['phase']
     return game
    def action(self, team_id, observation):
        """
        Chose an action at random, with a bias towards moving
        """
        action_types = [item for item in ActionType]
        directions = [item for item in Direction]
        action_type = random.choices(action_types, weights=[10, 100, 1])[0]

        if action_type == ActionType.MOVE:
            direction = random.choices(directions)[0]
        else:
            direction = None

        action = Action(action_type, direction)
        return action
Exemple #28
0
    def do_action(self, action):
        """
        First, extract lines according to user's input, within each line holds the coordinate of each tile
        Then, move and merge tiles
        :param action:
        :return:
        """
        lines = self._get_lines(action=action)

        self._game_board.merge_tile(
            lines=lines, merge_to_left=Action.left_direction(action))

        self._move_count += 1

        self._weighted_score = float(self._game_board.get_score()) / float(
            self._move_count)
    def action(self, team_id, observation):
        if self.random_steps > 0:  # super smart way of avoiding to get stuck ;)
            self.random_steps -= 1
            return self.random_action

        self.parse(observation, team_id)

        if self.resources > 0 or self.health <= 2:
            # return to base
            _, target_x, target_y = self.find_item("BASE")
        else:
            # find some resource
            resource, target_x, target_y = self.find_item("RESOURCE")
            if resource is None:
                return Action(ActionType.STOP)
        return self.path_find(target_x, target_y)
Exemple #30
0
def handle_movement_keys(key):
    action: [Action, None] = None

    if key == tcod.event.K_u:
        action = Action(ActionType.MOVEMENT, dx=0, dy=-1)
    elif key == tcod.event.K_j:
        action = Action(ActionType.MOVEMENT, dx=0, dy=1)
    elif key == tcod.event.K_k:
        action = Action(ActionType.MOVEMENT, dx=1, dy=0)
    elif key == tcod.event.K_h:
        action = Action(ActionType.MOVEMENT, dx=-1, dy=0)
    elif key == tcod.event.K_y:
        action = Action(ActionType.MOVEMENT, dx=-1, dy=-1)
    elif key == tcod.event.K_i:
        action = Action(ActionType.MOVEMENT, dx=1, dy=-1)
    elif key == tcod.event.K_n:
        action = Action(ActionType.MOVEMENT, dx=-1, dy=1)
    elif key == tcod.event.K_m:
        action = Action(ActionType.MOVEMENT, dx=1, dy=1)

    return action
Exemple #31
0
    def create_new_job(self, created_actions: List[ActionToCreate]):
        """Creates a job that will be performed on the songs
            """
        created_job: List[Action] = []
        for index, created_action in enumerate(created_actions):
            action = Action(created_action, self.job_index, index)
            action.signals.action_started.connect(self.set_action_length)
            action.signals.action_progress\
                .connect(self.update_action_progress)
            action.signals.action_finished\
                .connect(self.update_action_complete)
            if action.subaction_signals is not None:
                action.subaction_signals.subaction_started\
                    .connect(self.set_subaction_length)
                action.subaction_signals.subaction_progress\
                    .connect(self.update_subaction_progress)
                action.subaction_signals.subaction_finished\
                    .connect(self.update_subaction_complete)
            created_job.append(action)

        self.add_to_current_jobs(created_job)
Exemple #32
0
import json
from actions import Action

print "Running HoursFillerCmd"


act = Action()

act.login()


act.remove_all_existing()

exit(0)



d = dict(project="GO-LAB", unit="Unidad Internet", concept="I+D Desarrollo Proyecto", date="1/1/2014", hours="1")
act.add_entry(**d)
act.add_entry(**d)
act.add_entry(**d)


entries_raw = open("entries.json").read()
entries = json.loads(entries_raw)

act.add_entries(entries["entries"])
Exemple #33
0
    def doDealDamage(self, list, combat=False):

        dr = DamageReplacement(list, combat)
        self.raise_event("damage_replacement", dr)

        for a_lki_id, b_lki_id, n in dr.list:
            if not self.lki(b_lki_id).is_moved():

                # go through all applicable damage prevention effects
                applicable = []
                for damage_prevention in self.damage_preventions:
                    if damage_prevention.canApply(self, (a_lki_id, b_lki_id, n), combat):
                        applicable.append (damage_prevention)

                while len(applicable) > 0:
                    # do we have a unique applicable effect?
                    if len(applicable) == 1:
                        a_lki_id,b_lki_id,n = applicable[0].apply(self, (a_lki_id, b_lki_id, n), combat)
                        applicable = []
                    else:
                        # we let the reciever's controller choose
                        # TODO: make threadless
                        controller = self.objects[self.lki(b_lki_id).get_controller_id()]

                        actions = []
                        for damage_prevention in applicable:
                            action = Action()
                            action.text = damage_prevention.getText()
                            action.damage_prevention = damage_prevention
                            actions.append(action)

                        _as = ActionSet (self, controller, "Which damage prevention effect apply first for %d damage to %s?" % (n, str(self.lki(b_lki_id))), actions)
                        action = self.input.send (_as)

                        damage_prevention = action.damage_prevention

                        a_lki_id,b_lki_id,n = damage_prevention.apply(self, (a_lki_id,b_lki_id,n), combat)
                        applicable.remove(damage_prevention)

                        if n <= 0:
                            break

                        new_applicable = []
                        for damage_prevention in applicable[:]:
                            if damage_prevention.canApply(self, (a_lki_id,b_lki_id,n), combat):
                                new_applicable.append(damage_prevention)
                        applicable = new_applicable


                if n <= 0:
                    continue

                if combat:
                     self.raise_event("pre_deal_combat_damage", a_lki_id, b_lki_id, n)

                self.raise_event("pre_deal_damage", a_lki_id, b_lki_id, n)

                a = self.lki(a_lki_id)
                b = self.lki(b_lki_id)
                if "player" in b.get_state().types:
                    if "damage that would reduce your life total to less than 1 reduces it to 1 instead" in b.get_state().tags and (b.get_object().life - n < 1):
                        b.get_object().life = 1
                    else:
                        b.get_object().life -= n
                else:
                    b.get_object().damage += n

                self.output.damage(a.get_object(), b.get_object, n)

                if combat:
                     self.raise_event("post_deal_combat_damage", a_lki_id, b_lki_id, n)

                self.raise_event("post_deal_damage", a_lki_id, b_lki_id, n)
Exemple #34
0
    def on_receive(self, msg):
        logger.debug("Received admin command: %s" % msg)

        cmd = msg.get('command', '')
        if cmd.count('.') == 1:
            subject, action = cmd.split('.')

            # hosts
            if subject == 'hosts':

                # .list
                if action == 'list':
                    return {'hosts': [n.to_json() for n in Session.query(Host).filter(Host.acknowledged==True)]}

                # .details
                elif action == 'details':
                    host = Session.query(Host).filter(Host.id==msg['args'][0]).first()
                    return {'host': host.to_json()}

            # autohosts
            elif subject == 'autohosts':

                # .list
                if action == 'list':
                    return {'hosts': [n.to_json() for n in Session.query(Host).filter(Host.acknowledged==False)]}

                # .add
                elif action == 'add':
                    host = Session.query(Host).filter(Host.id==msg['args'][0]).first()
                    host.acknowledged = True
                    host.key = uuid4()
                    Session.add(host)
                    Session.commit()
                    return {'key': host.key}

                # .decline
                elif action == 'decline':
                    host = Session.query(Host).filter(Host.id==msg['args'][0]).first()
                    Session.delete(host)
                    Session.commit()
                    return {}

            # values
            elif subject == 'values':

                # .latest
                if action == 'latest':
                    host = Session.query(Host).filter(Host.id==msg['args'][0]).first()
                    return {'values': [v.to_json() for v in host.reports[-1].values.all()]}

            # triggers
            elif subject == 'triggers':

                # .list
                if action == 'list':
                    return {'triggers': [t.to_json() for t in Session.query(Trigger).all()]}

                # .add
                if action == 'add':
                    trigger = Trigger(
                        host_id     = msg['args'][0]['host'],
                        name        = msg['args'][0]['name'],
                        description = msg['args'][0]['description'],
                        expression  = msg['args'][0]['expression'],
                        action      = msg['args'][0]['action']
                    )
                    Session.add(trigger)
                    Session.commit()
                    return {'id': trigger.id}

            # actions
            elif subject == 'actions':

                # .list
                if action == 'list':
                    return {'actions': Action.get_actions()}

        else:
            raise PackageError('Missing or invalid command')
 def post(self):
   user = users.get_current_user()
   if not user:
     self.error(403) # access denied
     return
   
   client = get_client(user)
   if not client:
     self.error(403) # access denied
     return
   
   #debug = self.request.get('debug', False)
   
   
   # CAUTION: IT WANNA BE BY ANOTHER WAY (NEED TO IMPLEMENT)
   #char.logged = True
   #char.put()
   
   #self.response.headers.add_header("Content-Type", 'application/json')
   
   # Action to execute
   action = self.request.get('action')
   
   # Arguments of the action
   args = self.request.get_all('args[]')
   # REMOVE ALL EMPTY VALUE OF THE ARGS
   for i in range(args.count('')):
     args.remove('')
   
   
   # Target of the action
   target_id = self.request.get('target')
   if target_id:
     target = db.get(db.Key(target_id))
     # DEBUG
     if not target:
       response['alert'].append('TARGET NOT AVAILABLE')
   else:
     target = None
   
   
   # Client time that executed the action
   client_time = self.request.get('time')
   
   # Append to the response the action feedback or one alert or error if it has
   response = {
                 'action': action,
                 'target': target,
                 'args': args,
                 'client_time': client_time,
                 #'server_hour': datetime.datetime.now().strftime('%I:%M:%S'),
                 'self': client.char.id,
                 #'object': {}, Thinking about it here in action_handler
                 #'listener': {}, Not implemented yet
                 'alert': [],
                 'error': [],
               }
   
   
   if action == 'ping':
     pass
   
   elif action == 'get_channel_token':
     client.channel_token = create_channel(client.id)
     client.put()
     response['channel_token'] = client.channel_token
   
   elif action in actions_signatures:
     #response['alert'].append('Action found:' + action)
     if validate_args(actions_signatures[action], args):
       #function = getattr(actions, action)
       #function(client, response, args)
       query = db.Query(Action)
       query.filter('active =', True)
       query.filter('action =', action)
       query.filter('char =', client.char)
       saved_action = query.get()
       if saved_action:
         response['alert'].append('ACTION ACTIVE FOUND')
         saved_action.args = args
         saved_action.target = target
         saved_action.put()
       else:
         response['alert'].append('NEW ACTION CREATED')
         action = Action(char=client.char,
                         action=action,
                         args=args,
                         target=target)
         action.put()
         
       
     else:
       response['error'].append('ERROR TO VALIDATE ARGS')
   
   else:
     response['error'].append('ACTION NOT ALLOWED')
   
   self.response.out.write(simplejson.dumps(response))
   return
Exemple #36
0
 def test_Action_run(self, run):
     action = Action([Step('url1'), Step('url2')])
     action.run()
     self.assertEqual(run.call_count, 2)
Exemple #37
0
# Full script.
from actions import Action
import config

if __name__ == "__main__":

    # Load the calendar.
    import json
    import optimize

    calendar = json.loads(open("dt.json").read())
    split = json.loads(open("my.split.json").read())
    entries = optimize.split_to_entries(calendar, split)


    act = Action()
    act.login()

    if config.REMOVE_BEFORE_ADD:
        act.remove_all_existing()

    act.add_entries_safe(entries, "my.progress.json")