Ejemplo n.º 1
0
 def post(self, key=None):
     server = self.get_server_by_key(key, abort=False)
     if server is None:
         self.redirect_to_server('home')
         return
     try:
         form = CommandForm(self.request.POST)
         if form.validate():
             command = form.command.data
             username = self.request.user.get_server_play_name(server.key)
             if command and command.startswith(u'/say '):
                 if len(command) <= 5:
                     command = None
                 elif username:
                     command = u"/say <{0}> {1}".format(username, command[5:])
             if command:
                 Command.push(server.key, username, command)
                 message = u'Command "{0}" sent to world "{1}".'.format(command, server.name)
                 logging.info(message)
                 self.session.add_flash(message, level='info')
                 time.sleep(1)
     except Exception, e:
         message = u'Command "{0}" could not be send to world "{1}" (Reason: {2}).'.format(command, server.name, e)
         logging.error(message)
         self.session.add_flash(message, level='error')
Ejemplo n.º 2
0
def cmd_execute_asset():
    # print request.form
    _is_ok, _errors = Command.validate(request.form,
                                       session['user']['username'])
    _success = ''
    if _is_ok:
        _is_ok, _success = Command.execute(request.form)
        if _is_ok:
            return json.dumps({
                '_is_ok': _is_ok,
                'errors': _errors,
                'success': _success
            })
        else:
            return json.dumps({
                '_is_ok': _is_ok,
                'errors': {
                    'sys': '请检查系统用户名密码和连接'
                },
                'success': _success
            })
    return json.dumps({
        '_is_ok': _is_ok,
        'errors': _errors,
        'success': _success
    })
Ejemplo n.º 3
0
def parse_client_input(message: str,
                       client: Client) -> tuple[Optional[Command], str]:
    if not message.startswith('/'):
        return None, 'Enter command'

    split_command = message[1:].split(' ')

    if len(split_command) == 0:
        return None, 'No such command'

    if len(split_command) == 1:
        if split_command[0] == Commands.QUITE:
            command = Command(sender=client, command=Commands.QUITE)
            return command, ''
        elif split_command[0] == Commands.ROOMS:
            command = Command(sender=client, command=Commands.ROOMS)
            return command, ''
        else:
            return None, f'Command {split_command[0]} requires more then 0 params.'

    try:
        command_name = Commands(split_command[0])
    except ValueError:
        return None, 'No such command'

    command = Command(sender=client,
                      command=command_name,
                      body=' '.join(split_command[1:]))
    return command, ''
Ejemplo n.º 4
0
def cmd_execute_asset():
    _is_ok, _errors = Command.validate(request.form)
    _success = ''
    if _is_ok:
        _success = Command.execute(request.form)
    return json.dumps({
        'is_ok': _is_ok,
        'errors': _errors,
        'success': _success
    })
Ejemplo n.º 5
0
def comment(command_args, account):    
    cc = Comment(body = command_args,
                 task = account.task,
                 created = datetime.datetime.now())
    cc.put()
    
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="COMMENT",
                      args=command_args,
                      task=account.task)
                      
    command.put()
Ejemplo n.º 6
0
def cmd_execute_asset():
    _is_ok, _errors = Command.validate(request.form)
    _id = request.form.get('id', '')
    _count, _asset = asset.get_by_id(_id)
    _success = ''
    if _is_ok:
        _success = Command.execute(request.form, _asset[0])
        print _success
    return json.dumps({
        'is_ok': _is_ok,
        'errors': _errors,
        'success': _success
    })
Ejemplo n.º 7
0
def comment(command_args, account):
    cc = Comment(body=command_args,
                 task=account.task,
                 created=datetime.datetime.now())
    cc.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="COMMENT",
                      args=command_args,
                      task=account.task)

    command.put()
Ejemplo n.º 8
0
def pop(command_args, account):
    tobepopped = account.task
    tobepopped.status = db.Category("finished")
    tobepopped.put()
    
    account.task = account.task.blocks
    account.put()
    
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="POP",
                      args=command_args,
                      task=tobepopped)
    command.put()
Ejemplo n.º 9
0
def switch(command_args, account):

    uuid = command_args.strip()
    task = Task.all().filter("uuid =", uuid)[0]
    task.status = db.Category("underway")
    account.task = task
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="SWITCH",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 10
0
def pop(command_args, account):
    tobepopped = account.task
    tobepopped.status = db.Category("finished")
    tobepopped.put()

    account.task = account.task.blocks
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="POP",
                      args=command_args,
                      task=tobepopped)
    command.put()
Ejemplo n.º 11
0
 def post(self, server_key, key_username=None):
     server_key = self.get_server(server_key).key
     username = self.request.user.get_server_play_name(server_key)
     if key_username:
         player = self.get_player_by_key_or_username(server_key, key_username)
         username = player.username
         if username not in self.request.user.usernames:
             self.abort(403)
     if username:
         chat = u"/say <{0}> {1}".format(username, self.request.form.chat.data)
     else:
         chat = u"/say {0}".format(self.request.form.chat.data)
     Command.push(server_key, username, chat)
     self.response.set_status(202)
Ejemplo n.º 12
0
def switch(command_args, account):
    
    uuid = command_args.strip()
    task = Task.all().filter("uuid =", uuid)[0]
    task.status = db.Category("underway")
    account.task = task
    account.put()
    
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="SWITCH",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 13
0
def up(command_args, account):
    if not account.task:
        return
        
    toblock = account.task
    
    account.task = account.task.blocks
    account.put()
    
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="UP",
                      args=command_args,
                      task=toblock)
    command.put()
Ejemplo n.º 14
0
def up(command_args, account):
    if not account.task:
        return

    toblock = account.task

    account.task = account.task.blocks
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="UP",
                      args=command_args,
                      task=toblock)
    command.put()
Ejemplo n.º 15
0
def addnewcommand():
    if 'username' not in session:
        return redirect(url_for('login'))

    data = request.get_data()
    data = str(data)
    data = data.strip('b').split('&')
    x, y = [], []
    if request.method == 'POST':
        for i in data:
            #print(i.split('=')[1].rstrip("'").replace("+", " "))
            x.append(i.split('=')[1].rstrip("'").replace("+", " "))
        command, name, desc = x[0], x[1], x[2]
        print(command, name, desc)
        newcommand = Command(command, name, desc)
        print(newcommand, command, name, desc, "demello")
        try:
            db.session.add(newcommand)
            db.session.commit()
            return render_template('addnewcommand.html',
                                   success_msg="Command added successfully")
        except:
            return render_template(
                'addnewcommand.html',
                fail_msg="Error occured.Can not add new command")
    return render_template('addnewcommand.html')
Ejemplo n.º 16
0
def index(request):
    if 'offset' in request.GET:
        offset = int(request.GET['offset'])
    else:
        offset = 0
    
    # use Users API to get current user
    user = users.get_current_user()
    
    # if a user is logged in, redirect to their workstack page
    if not user:
      greeting = ("<a href=\"%s\">Sign in or register</a>." %
                  users.create_login_url("/"))
      return HttpResponse("<html><body><h1>Workstack</h1>%s</body></html>"%greeting)
    
    logout_url = users.create_logout_url("/")
    
    commands = Command.all().filter("user ="******"blocks =",account.task).filter("status =",db.Category("todo"))
    slushtasks = Task.all().filter("proposer =", user).filter("blocks =", None).filter("status =",db.Category("todo"))
    
    stack = []
    tt = account.task
    while tt is not None:
        stack.append( tt )
        tt = tt.blocks
        
    for i, task in enumerate(reversed(stack)):
        task.level = i

    return render_to_response( "index.html", {'account':account, 'commands':commands, 'user':user, 'logout_url':logout_url,'todos':todos,'stack':stack,'offset':offset+50,'slushtasks':slushtasks} )
Ejemplo n.º 17
0
def test_create_command(command, client, dep_overrider, mock_cmd_factory):
    from unittest.mock import MagicMock

    from google.cloud.firestore_v1 import AsyncDocumentReference

    from apis.v1.deps.command_deps import fs_ref_from_command

    client_mock = MagicMock(spec_set=AsyncDocumentReference)
    snap = mock_cmd_factory(command)

    async def return_ref(name, game: int):
        assert name == command.name
        assert game == command.game
        return snap.reference

    with dep_overrider(fs_ref_from_command, return_ref):
        resp = client.post(
            "/v1/commands",
            params={
                "name": command.name,
                "game": command.game
            },
            data=command.json(),
        )
    assert Command.parse_raw(resp.content) == command
Ejemplo n.º 18
0
def broadcast():
    """
    Description: Push the command into all the bots in the database 

    [POST]
        - masterkey = Masterkey to validate and authenticate master
        - command = Actual command to be pushed to the entire bots 
    """

    # Error checking
    error = posterrorcheck(request, 'masterkey', 'cmd')
    if error is not True:
        return error

    # POST parameter parsing
    data = request.form
    masterkey = data['masterkey']
    command = data['cmd']

    # API Endpoint logic
    bots = Bot.query.all()

    try:
        for bot in bots:
            cmd = Command(command, bot.id, bot.ip)
            bot.cmds.append(cmd)
            db.session.add(cmd)
            db.session.commit()

    except Exception as e:
        return jsonify({'error': str(e)})

    return jsonify({'result': '[+] Broadcast successful'})
Ejemplo n.º 19
0
def slush(command_args, account):
    title = command_args

    task = Task(proposer=account.user,
                proposed=datetime.datetime.now(),
                title=title,
                uuid=uuid.uuid1().hex,
                status=db.Category("todo"),
                blocks=None)
    task.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="SLUSH",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 20
0
def todo(command_args, account):
    title = command_args
    
    task = Task(proposer=account.user,
                proposed=datetime.datetime.now(),
                title=title,
                uuid=uuid.uuid1().hex,
                status=db.Category("todo"),
                blocks = account.task)
    task.put()
    
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="TODO",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 21
0
def command():
    form = CommandForm()
    if form.validate_on_submit():
        command = form.command_input.data
        cmd = Command(command=command, user_id=session['user_id'])
        db.session.add(cmd)
        db.session.commit()
        return redirect(url_for('view', cmd_string=command))
    return render_template("command.html", form=form)
Ejemplo n.º 22
0
def push(command_args, account):
    title = command_args

    task = Task(proposer=account.user,
                proposed=datetime.datetime.now(),
                title=title,
                uuid=uuid.uuid1().hex,
                status=db.Category("underway"),
                blocks=account.task)
    task.put()

    account.task = task
    account.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="PUSH",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 23
0
def push(command_args, account):
    title = command_args
    
    task = Task(proposer=account.user,
                proposed=datetime.datetime.now(),
                title=title,
                uuid=uuid.uuid1().hex,
                status=db.Category("underway"),
                blocks = account.task)
    task.put()

    account.task = task
    account.put()
    
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="PUSH",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 24
0
 def make_mock_snap(cmd: Command) -> DocumentSnapshot:
     ref = AsyncDocumentReference(*cmd.document_path.split("/"))
     # noinspection PyTypeChecker
     snap = DocumentSnapshot(
         reference=ref,
         data=cmd.to_snap(),
         exists=True,
         read_time=None,
         create_time=None,
         update_time=None,
     )
     return snap
Ejemplo n.º 25
0
 def post(self, server_key=None):
     server = self.get_server_by_key(server_key, abort=False)
     if server is None:
         self.redirect_to_server('chats')
         return
     try:
         user = self.request.user
         if not (user and user.active):
             self.abort(404)
         form = ChatForm(self.request.POST)
         if form.validate():
             chat = form.chat.data
             username = user.get_server_play_name(server.key)
             if chat:
                 if username:
                     chat = u"/say <{0}> {1}".format(username, chat)
                 else:
                     chat = u"/say {0}".format(chat)
                 Command.push(server.key, username, chat)
     except Exception, e:
         logging.error(u"Error POSTing chat: {0}".format(e))
         self.abort(500)
Ejemplo n.º 26
0
 def post(self, server_key=None):
     server = self.get_server_by_key(server_key, abort=False)
     if server is None:
         self.redirect_to_server('chats')
         return
     try:
         user = self.request.user
         if not (user and user.active):
             self.abort(404)
         form = ChatForm(self.request.POST)
         if form.validate():
             chat = form.chat.data
             username = user.get_server_play_name(server.key)
             if chat:
                 if username:
                     chat = u"/say <{0}> {1}".format(username, chat)
                 else:
                     chat = u"/say {0}".format(chat)
                 Command.push(server.key, username, chat)
     except Exception, e:
         logging.error(u"Error POSTing chat: {0}".format(e))
         self.abort(500)
Ejemplo n.º 27
0
def load_commands() -> List[Command]:
    with open("commands.json") as fp:
        commands = json.load(fp)
    cdict: Dict[str, Union[str, int]]
    cmds = []
    for cdict in commands:
        cmds.append(
            Command(
                name=cdict.get("Command").lstrip("!"),
                cooldown=cdict.get("Cooldown"),
                template=cdict.get("Response"),
                required_role=role_map.get(cdict.get("Permission")),
            ))
    return cmds
Ejemplo n.º 28
0
def command():
        content = request.form.get('command')

        # 通过前端传回的question_id,在再后端定位command的位置
        question_id = request.form.get('question_id')
        question = Questions.query.filter(Questions.id == question_id).first()
        user_id = session.get('user_id')
        user = User.query.filter(User.id == user_id).first()
        command = Command(content=content,author=user,question=question)

        db.session.add(command)
        db.session.commit()

        return redirect(url_for('detail',question_id = question_id))
Ejemplo n.º 29
0
def purpose(command_args, account):
    if not account.task:
        return
    
    uuids = command_args.strip().split()
    
    child_uuid = uuids[0]
    task_purpose = Task.all().filter("uuid =", child_uuid)[0]
    
    if len(uuids)==2:
        parent_uuid = uuids[1]
        task = Task.all().filter("uuid =", parent_uuid)[0]
    else:
        task = account.task
        
    task.blocks = task_purpose
    task.put()
        
    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="PURPOSE",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 30
0
def purpose(command_args, account):
    if not account.task:
        return

    uuids = command_args.strip().split()

    child_uuid = uuids[0]
    task_purpose = Task.all().filter("uuid =", child_uuid)[0]

    if len(uuids) == 2:
        parent_uuid = uuids[1]
        task = Task.all().filter("uuid =", parent_uuid)[0]
    else:
        task = account.task

    task.blocks = task_purpose
    task.put()

    command = Command(user=account.user,
                      created=datetime.datetime.now(),
                      root="PURPOSE",
                      args=command_args,
                      task=task)
    command.put()
Ejemplo n.º 31
0
def index(request):
    if 'offset' in request.GET:
        offset = int(request.GET['offset'])
    else:
        offset = 0

    # use Users API to get current user
    user = users.get_current_user()

    # if a user is logged in, redirect to their workstack page
    if not user:
        greeting = ("<a href=\"%s\">Sign in or register</a>." %
                    users.create_login_url("/"))
        return HttpResponse("<html><body><h1>Workstack</h1>%s</body></html>" %
                            greeting)

    logout_url = users.create_logout_url("/")

    commands = Command.all().filter("user ="******"blocks =",
                              account.task).filter("status =",
                                                   db.Category("todo"))
    slushtasks = Task.all().filter("proposer =", user).filter(
        "blocks =", None).filter("status =", db.Category("todo"))

    stack = []
    tt = account.task
    while tt is not None:
        stack.append(tt)
        tt = tt.blocks

    for i, task in enumerate(reversed(stack)):
        task.level = i

    return render_to_response(
        "index.html", {
            'account': account,
            'commands': commands,
            'user': user,
            'logout_url': logout_url,
            'todos': todos,
            'stack': stack,
            'offset': offset + 50,
            'slushtasks': slushtasks
        })
Ejemplo n.º 32
0
def test_get_command(command, client, dep_overrider, mock_cmd_factory):
    from apis.v1.deps.command_deps import fs_snap_exists

    snap = mock_cmd_factory(command)

    async def return_snap(name, game: int):
        assert name == command.name
        assert game == command.game
        return snap

    with dep_overrider(fs_snap_exists, return_snap):
        resp = client.get("/v1/commands",
                          params={
                              "name": command.name,
                              "game": command.game
                          })
    assert Command.parse_raw(resp.content) == command
Ejemplo n.º 33
0
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        data_json = json.loads(data)

        if 'command' in data_json:
            print(data_json["command"])
            if data_json["command"] == "microphone_adjustment":
                micPlugged = 0
                while micPlugged == 0:
                    micPlugged = checkMic().returncode
                    if micPlugged == 1:
                        print('Mic is plugged')
                        await websocket.send_json(
                            json.dumps(
                                Command(command='mic_plugged',
                                        value=True).__dict__))

        await websocket.send_json(data)
Ejemplo n.º 34
0
 def post(self):
     form = self.request.form
     is_server_running = form.is_server_running.data
     server_day = form.server_day.data
     server_time = form.server_time.data
     is_raining = form.is_raining.data
     is_thundering = form.is_thundering.data
     num_overloads = form.num_overloads.data
     ms_behind = form.ms_behind.data
     skipped_ticks = form.skipped_ticks.data
     address = form.address.data
     timestamp = form.timestamp.data
     client = Client.get_by_client_id(self.request.authentication.client_id)
     server = client.server
     if not server.active:
         self.abort(404)
     status = SERVER_UNKNOWN
     if is_server_running:
         status = SERVER_RUNNING
     elif is_server_running is False:
         status = SERVER_STOPPED
     server.update_status(
         status=status,
         last_ping=datetime.datetime.utcnow(),
         server_day=server_day,
         server_time=server_time,
         is_raining=is_raining,
         is_thundering=is_thundering,
         num_overloads=num_overloads,
         ms_behind=ms_behind,
         skipped_ticks=skipped_ticks,
         address=address,
         timestamp=timestamp
     )
     commands = []
     if is_server_running:
         commands = Command.pop_all(server.key)
     response = {
         'commands': commands
     }
     self.json_response(response, status_code=200)
Ejemplo n.º 35
0
def botpush(target):
    """
    Description: Pushes the command into the bot and cmd Model. 
    The command pushed into the bot and cmd model will later be used in the /task endpoint. 

    target = bot ID to push commands into 

    Params:
        - masterkey : Master's secret key 
        - cmd : Command to push to the bot 

    returns:
        - (json) result : 'Command staged' upon successfully staging the command 
        - (json) error : error  
    """

    # Error checking
    error = posterrorcheck(request, 'masterkey', 'cmd')
    if error is not True:
        return error

    # POST parameter parsing
    data = request.form
    masterkey = data['masterkey']
    cmd = data['cmd']

    bot_ip = ''
    bot_id = -1

    if re.match(r'(\d+\.?){4}\\?$', target):
        bot_ip = target
    else:
        bot_id = target

    # API Endpoint logic

    # Find bot based on bot ID (ip is deprecated) and push command
    try:
        if bot_ip != '':
            query_bot = Bot.query.filter_by(ip=bot_ip).first()
        else:
            query_bot = Bot.query.filter_by(id=bot_id).first()

        # Create command model based on the information
        cmd = Command(cmd, query_bot.id, query_bot.ip, query_bot.os)

        # Actually push the command to the bot.
        # If there is a previous command queued (making len(query_bot.cmds) >=1 ), ignore.
        try:
            query_bot.cmds.append(cmd)
            db.session.add(cmd)
            db.session.commit()

            return jsonify({'result': 'Command staged'})

        except Exception as e:
            return jsonify({'error': 'Error occurred while staging command'})

    except Exception as e:
        return jsonify(
            {'error': '[-] Pushing command for bot failed. ' + str(e)})
Ejemplo n.º 36
0
def process_commands(db_session, client, message):
    user = db_session.query(User).filter(User.uid == message.author.id).first()
    # here we want to split the commands up by pipes
    # we also want to pull commands from the hard coded ones, or the composite commands in the Command table (that are user defined)
    if message.content.startswith('!'):
        content = message.content[1:]
    else:
        content = ' '.join(message.content.split(' ')[1:])

    # for now, if command starts with !s/ IGNORE IT
    if content.split(' ')[0].lower().startswith('s/'):
        return ""
    # different case for alias command
    if content.split(' ')[0].lower() == 'alias':
        command_name = content.split(' ')[1].lower()
        if command_name == 'alias':
            return "Command already exists: alias."
        else:
            exist_command = db_session.query(Command).filter(
                Command.name == command_name).one_or_none()
            if exist_command:
                return f"Command already exists: {command_name}."
        command_string = ' '.join(content.split(' ')[2:])
        if 'alias' in command_string:
            return "Can't use alias command inside alias command."
        else:
            new_command = Command(user_id=user.id,
                                  name=command_name,
                                  description='',
                                  command_string=command_string)
            db_session.add(new_command)
            db_session.commit()
            return f"Added command: {command_name}."

    commands = content.split('|')
    commands = [c.strip() for c in commands]
    # iterate through commands until all of them have been transformed down to their hard coded version
    idx = 0
    depth = 0
    while idx < len(commands):
        depth += 1
        if depth == 1001:
            return 'Max loop depth reached (what did you do?!).'
        command = commands.pop(idx).strip()
        # get first word
        words = command.split(' ')
        initial = words[0].lower()
        rest = None
        if len(words) > 1:
            rest = words[1:]

        if initial in function_names:
            commands.insert(idx, command)
            idx += 1
        else:
            db_entry = db_session.query(Command).filter(
                Command.name == initial).one_or_none()
            if db_entry is None:
                if initial == 'alias':
                    return 'Alias can only be used as a standalone command.'

                bot_username = client.user.name.lower()
                mg = message.content.lower()
                if mg.startswith('iris ') or mg.startswith(
                        f"<@!{client.user.id}> ") or mg.startswith(
                            bot_username + ' '):
                    return ''
                return f'Command not found: {initial}'

            command_string = db_entry.command_string
            new_command = command_string
            highest = 0
            if len(new_command.split(' ')) > 1:
                tail_command = new_command.split(' ')[1:]
                for a in tail_command:
                    m = re.match('<([0-9]+)>', a)
                    if m:
                        num = int(m.group(1))
                        if num > highest:
                            highest = num

                if highest > 0:
                    for i in range(highest):
                        if rest and len(rest) > 0:
                            current = rest.pop(0)
                            indices = [
                                idx for idx, x in enumerate(tail_command)
                                if x == '<' + str(i + 1) + '>'
                            ]
                            for ind in indices:
                                tail_command[ind] = current
                        elif rest:
                            return f'Not enough arguments supplied'

            new_command = new_command.split(' ')[0] + ' ' + ' '.join(
                tail_command)

            if not rest == None:
                new_command += ' ' + ' '.join(rest)

            new_commands = new_command.split('|')
            commands = commands[:idx] + new_commands + commands[idx:]

    # input placeholders given by <1> <2> etc, if none given, assume output of previous command goes to final input(s) of next command
    outputs = []
    for command in commands:
        command_name = command.split(' ')[0]
        func = [o[1] for o in functions_list if o[0] == command_name][0]
        args = command.split(' ')[1:]
        args = [a.strip() for a in args]

        # get highest placeholder num in args

        for idx, o in enumerate(outputs):
            if is_non_str_iterable(o):
                o = "\n".join(o)

            pos_string = f'<{idx+1}>'
            if pos_string not in args:
                args.extend(o.split())
            else:
                indices = [
                    idx for idx, x in enumerate(args) if x == pos_string
                ]
                for ind in indices:
                    args = args[:ind] + o.split() + args[ind + 1:]
        reply = func(db_session, message, *args)
        outputs.extend(reply)

    output_message = outputs[-1]
    if is_non_str_iterable(output_message):
        output_message = [truncate_message(m) for m in output_message]
    else:
        output_message = truncate_message(output_message)
    return output_message
Ejemplo n.º 37
0
 def test_post(self):
     self.log_in_user()
     response = self.post(params={'chat': 'test'})
     self.assertCreated(response)
     self.assertEqual(1, Command.query().count())
Ejemplo n.º 38
0
    def create(self, the_parsed_component_xml, parsed_port_xml_list, parsed_serializable_list):
        """
        Create a component model here.
        """
        x = the_parsed_component_xml
        comp_obj = x.get_component()
        comp_port_obj_list = x.get_ports()
        comp_command_obj_list = x.get_commands()
        comp_channel_obj_list = x.get_channels()
        comp_parameter_obj_list = x.get_parameters()
        comp_event_obj_list = x.get_events()
        comp_internal_interface_obj_list = x.get_internal_interfaces()
        
        #
        comp_namespace = comp_obj.get_namespace()
        comp_name      = comp_obj.get_name()
        comp_kind      = comp_obj.get_kind()
        comp_comment   = comp_obj.get_comment()
        comp_modeler  = comp_obj.get_modeler()
        if comp_namespace == None:
            comp_full_name = comp_name
        else:
            comp_full_name = comp_namespace + "::" + comp_name  
        # get original filename here...
        comp_xml_filename = x.get_xml_filename()
        #
        comp_xml_port_files = x.get_port_type_files()
        comp_c_header_files = x.get_header_files()
        has_guarded_ports = False
        
        num_async_ports = 0
        num_sync_ports = 0 # includes guarded ports
        
        #
        #print ("Component: %s"%comp_name)
        incl_list = []
        #
        # Create list of ports with all ports of the component.
        #
        port_obj_list = []
        for port_obj in comp_port_obj_list:
            n=port_obj.get_name()
            t=port_obj.get_type()
            d=port_obj.get_direction()
            s=port_obj.get_sync()
            r=port_obj.get_role()
            if (s == 'sync' or s == 'guarded'):
                num_sync_ports += 1
            if s == 'async':
                num_async_ports += 1
            p=port_obj.get_priority()
            if s == "guarded":
                has_guarded_ports = True
            c=port_obj.get_comment()
            m=port_obj.get_max_number()
            f=port_obj.get_full()
            port_obj_list.append(Port.Port(n, t, d, s, p, f, c, max_number=m, role=r ))
        command_obj_list = []
        for command_obj in comp_command_obj_list:
            m=command_obj.get_mnemonic()
            o=command_obj.get_opcodes()
            s=command_obj.get_sync()
            p=command_obj.get_priority()
            f=command_obj.get_full()
            if s == "guarded":
                has_guarded_ports = True
            if (s == 'sync' or s == "guarded"):
                num_sync_ports += 1
            if s == 'async':
                num_async_ports += 1
            c=command_obj.get_comment()
            arg_obj_list = []
            for a in command_obj.get_args():
                name    = a.get_name()
                atype   = a.get_type()
                comment = a.get_comment()
                size    = a.get_size()
                arg_obj_list.append(Arg.Arg(name, atype, None, size, comment))
            command_obj_list.append(Command.Command(m, o, arg_obj_list, s, p, c, comp_xml_filename,comp_full_name , component_base_name = comp_name , base_opcode = command_obj.get_base_opcode() , full  = f))
            
            
        channel_obj_list = []
        for channel_obj in comp_channel_obj_list:
            i=channel_obj.get_ids()
            n=channel_obj.get_name()
            t=channel_obj.get_type()
            s=channel_obj.get_size()
            c=channel_obj.get_comment()
            a=channel_obj.get_abbrev()
            f=channel_obj.get_format_string()
            u=channel_obj.get_update()
            l=channel_obj.get_limits()
            channel_obj_list.append(
                Channel.Channel(ids=i, 
                                name=n, 
                                ctype=t, 
                                size=s, 
                                abbrev=a, 
                                format_string=f, 
                                update=u,
                                limits=l,
                                comment=c,
                                xml_filename=comp_xml_filename,
                                component_name=comp_full_name,
                                component_base_name = comp_name))
        
        event_obj_list = []
        for event_obj in comp_event_obj_list:
            i=event_obj.get_ids()
            n=event_obj.get_name()
            s=event_obj.get_severity()
            f=event_obj.get_format_string()
            t=event_obj.get_throttle()
            c=event_obj.get_comment()
            arg_obj_list = []
            for a in event_obj.get_args():
                name    = a.get_name()
                atype   = a.get_type()
                size    = a.get_size()
                comment = a.get_comment()
                arg_obj_list.append(Arg.Arg(name, atype, None, size, comment))
            event_obj_list.append(Event.Event(i, n, s, f, t, arg_obj_list, c, comp_xml_filename,comp_full_name , component_base_name = comp_name))
            
        internal_interface_obj_list = []
        for internal_interface_obj in comp_internal_interface_obj_list:
            # borrow this for check
            num_async_ports += 1
            n=internal_interface_obj.get_name()
            p=internal_interface_obj.get_priority()
            f=internal_interface_obj.get_full()
            c=internal_interface_obj.get_comment()
            arg_obj_list = []
            for a in internal_interface_obj.get_args():
                name    = a.get_name()
                atype   = a.get_type()
                size    = a.get_size()
                comment = a.get_comment()
                arg_obj_list.append(Arg.Arg(name, atype, None, size, comment))
            internal_interface_obj_list.append(InternalInterface.InternalInterface(n, p, f , arg_obj_list, c, comp_xml_filename,comp_full_name))

        parameter_obj_list = []
        for parameter_obj in comp_parameter_obj_list:
            i=parameter_obj.get_ids()
            n=parameter_obj.get_name()
            t=parameter_obj.get_type()
            set_ops = parameter_obj.get_set_opcodes()
            save_ops = parameter_obj.get_save_opcodes()
            d=parameter_obj.get_default()
            s=parameter_obj.get_size()
            c=parameter_obj.get_comment()
            parameter_obj_list.append(Parameter.Parameter(i, n, t, set_ops, save_ops, d, s, c, comp_xml_filename,comp_full_name , base_setop = parameter_obj.get_base_setop() , base_saveop = parameter_obj.get_base_saveop()))
            
        serializable_obj_list = []
        for serializable_obj in parsed_serializable_list:
            f=serializable_obj.get_xml_filename()
            n=serializable_obj.get_name()
            ns=serializable_obj.get_namespace()
            c=serializable_obj.get_comment()
            x=serializable_obj.get_includes()
            # shouldn't be c includes
            m=serializable_obj.get_members()
            t=serializable_obj.get_typeid()
            serializable_obj_list.append(Serialize.Serialize(f,n,ns,c,x,None,m,t))
                    
        #
        # Check here to make sure all the port types in the component XML
        # exist in the port XMLs
        #
        interface_xml_list = [parsed_port_obj.get_interface().get_name() for parsed_port_obj in parsed_port_xml_list]
        for port_obj in port_obj_list:
            t = port_obj.get_type()
            ## Skip if special port. (If there role)
            ## Namespaces for special ports are set above
            if (t not in interface_xml_list) and (t.lower() != "serial") and (port_obj.get_role() == None):
                PRINT.info("ERROR: Missing port type definition in component XML (name: %s, type: %s)" % (port_obj.get_name(),t))
                sys.exit(-1)
        #
        # Check here to make sure all the port types in the component XML
        # exist in the port XMLs
        #

#        interface_xml_list = [parsed_command_obj.get_interface().get_name() for parsed_command_obj in parsed_command_xml_list]
#        print interface_xml_list
#        for command_obj in command_obj_list:
#            t = command_obj.get_type()
#            if (t not in interface_xml_list):
#                PRINT.info("ERROR: Missing command type definition in component XML (name: %s, type: %s)" % (command_obj.get_type(),t))
#                sys.exit(-1)
#       #
        # Add port type specifics to port object.
        # Specifics are things like: args, includes, etc.
        for port_obj in port_obj_list:

            for parsed_port_obj in parsed_port_xml_list:
                #print "Meta: Name: %s, Type: %s" % (port_obj.get_name(), port_obj.get_type())
                #print "Meta: Port Type: %s, Port Interface: %s" % (port_obj.get_type(),parsed_port_obj.get_interface().get_name())
                    
                if port_obj.get_type() == parsed_port_obj.get_interface().get_name():
                    arg_obj_list = []
                    incl_list = parsed_port_obj.get_include_header_files()
                    namespace = parsed_port_obj.get_interface().get_namespace()
                    if_comment = parsed_port_obj.get_interface().get_comment()
                    return_type = parsed_port_obj.get_interface().get_return_type()
                    return_modifier = parsed_port_obj.get_interface().get_return_modifier()
            
                    for a in parsed_port_obj.get_args():
                        name    = a.get_name()
                        atype   = a.get_type()
                        comment = a.get_comment()
                        modifier = a.get_modifier()
                        size = a.get_size()
                        arg_obj_list.append(Arg.Arg(name, atype, modifier, size, comment))
                    port_obj.set(namespace, arg_obj_list, incl_list, None, if_comment)
                    port_obj.set_return(return_type,return_modifier)
                    # check some rules
                    # 1) No return values for async ports
                    if (port_obj.get_sync() == "async") and (return_type != None):
                        PRINT.info("ERROR: %s: Port \"%s\" cannot be asynchronous and have a return value" % (the_parsed_component_xml.get_xml_filename(), port_obj.get_name()))
                        sys.exit(-1)
                    # 2) Serial ports can't have roles
                    if (port_obj.get_type() == "Serial") and (port_obj.get_role() != None):
                        PRINT.info("ERROR: %s: Port \"%s\" cannot have a role and be a serialized port" % (the_parsed_component_xml.get_xml_filename(), port_obj.get_name()))
                        sys.exit(-1)
                         
        # check some component/port rules
        # 1) Active or queued need at least one async port/command
        if (comp_kind == "active") or (comp_kind == "queued"):
            if num_async_ports == 0 and len(parameter_obj_list) == 0:
                PRINT.info("ERROR: %s: Active/Queued component \"%s\" needs at least one async port, command, or interface" % (the_parsed_component_xml.get_xml_filename(), comp_name))
                sys.exit(-1)
        # 2) Queued component needs at least one sync port/command
        if comp_kind == "queued":
            if num_sync_ports == 0:
                PRINT.info("ERROR: %s: Queued component \"%s\" needs at least one sync/guarded port or command" % (the_parsed_component_xml.get_xml_filename(), comp_name))
                sys.exit(-1)
                 

        #
        # Instance the component here...
        #
        the_component = Component.Component(comp_namespace, comp_name, comp_kind, comp_comment, comp_modeler, port_obj_list, command_obj_list, channel_obj_list, parameter_obj_list, event_obj_list, internal_interface_obj_list, serializable_obj_list, comp_xml_filename)
        the_component.set_xml_port_files(comp_xml_port_files)
        the_component.set_c_header_files(comp_c_header_files)
        if (has_guarded_ports):
            the_component.set_has_guarded_ports()
        
        #for p in the_component.get_ports():
        #    print p.get_name(), p.get_namespace()
        #    for a in p.get_args():
        #        print a.get_name(), a.get_type(), a.get_modifier()

        return the_component
Ejemplo n.º 39
0
                default='sqlite',
                help=
                "which type of database to use (postgres, sqlite). Defaults to sqlite."
            )
            module_parser.add_argument(
                '--db-config',
                help="Name of file containing database configuration.")

            # Each module defines additional arguments
            module.configure_parser(module_parser)
            module_parser.set_defaults(func=module.main)

    # Add command for running unit tests
    test_parser = subparsers.add_parser('tests', description="Run unit tests.")
    test_parser.set_defaults(func=run_tests)

    # Parse arguments
    args = parser.parse_args()

    # Initialize database
    if args.command != 'tests':
        init_database(args.db, config_filename=args.db_config)
        create_tables()

        # Save a record of this command that we can refer back to later if needed
        Command.create(arguments=str(sys.argv))

    # Invoke the main program that was specified by the submodule
    if args.func is not None:
        args.func(**vars(args))
Ejemplo n.º 40
0
    bulk_command_set = match.group(1)

    user = message['user']
    channel = message['channel']
    for command in [x.strip() for x in bulk_command_set.split('\n')]:
        print(f'Bulk command: \'{command}\'')
        handle_message({'text' : command, 'user' : user, 'channel' : channel})

    return "Bulk commands executed."

commands = [
    Command(
        pattern=r'^(?i)~newBlaymon (.+)$',
        method=new_blaymon,
        threaded=False,
        enabled=True,
        name='Add New Blaymon Message',
        syntax='~newBlaymon message',
        description='Adds a new potential response for !blaymon.',
        _class='Administration'
    ),
    Command(
        pattern=r'^(?i)~newHackThePlanet (.+)$',
        method=new_hack_the_planet,
        threaded=False,
        enabled=True,
        name='Add New "Hackers" Quote',
        syntax='~newHackThePlanet quote',
        description='Adds a new potential response for !hackThePlanet.',
        _class='Administration'
    ),
    Command(