Example #1
0
 def test_invul_error_time_before_now(self):
     """ MEDIC can only INVUL a time in the future """
     medic = self.p1c
     now = Util.utc_to_chi(datetime.now()) - timedelta(hours=1)
     params = ["p1a", str(now.month), str(now.day),\
             str(now.hour), str(now.minute)]
     with self.assertRaises(TimeError) as e:
         Invul.handler(medic, params)
     self.assertEqual(e.exception.message, "You cannot set {} before time {}."\
             .format(now.strftime("%m-%d %I:%M%p"),\
             Util.utc_to_chi(datetime.now()).strftime("%m-%d %I:%M%p")))
     self.assertEqual(len(self.invul_queue), 0)
Example #2
0
 def test_error_time_is_before_now(self):
     """ Attacker wants to set a bomb back in time """
     attacker = self.p1a
     now = Util.utc_to_chi(datetime.now()) - timedelta(hours=1)
     params = ["Here", str(now.month), str(now.day),\
             str(now.hour), str(now.minute)]
     with self.assertRaises(TimeError) as e:
         Bomb.handler(attacker, params)
     self.assertEqual(e.exception.message, "You cannot set {} before time {}."\
             .format(now.strftime("%m-%d %I:%M%p"),\
             Util.utc_to_chi(datetime.now()).strftime("%m-%d %I:%M%p")))
     self.assertEqual(len(self.bomb_queue), 0)
Example #3
0
 def test_good_invul(self):
     """ GOOD test """
     medic = self.p1c
     now = Util.utc_to_chi(datetime.now())
     params = self.default_params
     Invul.handler(medic, params)
     self.assertEqual(len(self.invul_queue),1)
Example #4
0
    def reply_handler(cls, action, response):
        if response == "Y" or response == "y":
            action.need_validation = False
            action.incorrect_kill = False
            action_key = action.put()

            victim = Player.get_by_id(action.victim)
            victim.disarm = True
            victim.put()

            disarm = Disarm()
            disarm.attacker = action.attacker
            disarm.victim = action.victim
            disarm.starttime = datetime.now()
            disarm.endtime = datetime.now() + timedelta(hours = 1)
            disarm_key = disarm.put()

            task = taskqueue.Task(url="/disarm", params={"id": disarm_key.id()},
                    eta=disarm.endtime)
            task.add(queue_name="disarm")
            q = taskqueue.Queue('disarm').fetch_statistics()
            logging.critical(q)

            return [(action.victim, "You have been DISARM until {}".format(\
                    Util.utc_to_chi(disarm.endtime).strftime("%m-%d %I:%M%p")))]
        else:
            action.need_validation = False
            action.incorrect_kill = False
            action.put()
            return [(action.attacker, "Your DISARM target claims he was not "
                "disarmed by you.")]
Example #5
0
 def test_good_bomb(self):
     """ Good attacker set good bomb. """
     attacker = self.p1a
     later = Util.utc_to_chi(datetime.now())
     params = self.default_params
     Bomb.handler(attacker, params)
     self.assertEqual(len(self.taskqueue_stub.get_filtered_tasks(\
             queue_names='bomb')), 1)
Example #6
0
 def test_error_attacker_bomb_time_invalid(self):
     """ Attacker wants to set a bomb but his bomb quota for today is expired"""
     attacker = self.p1a
     attacker.can_set_after = Util.next_day()
     params = self.default_params
     with self.assertRaises(TimeError) as e:
         Bomb.handler(attacker, params)
     self.assertEqual(e.exception.message, "You cannot set bomb before time {}.".\
             format(Util.utc_to_chi(attacker.can_set_after).strftime(\
             "%m-%d %I:%M%p")))
     self.assertEqual(len(self.bomb_queue), 0)
Example #7
0
 def test_invul_error_time_before_valid_time(self):
     """ MEDIC can only INVUL one person per 24 hour period """
     medic = self.p1c
     medic.can_set_after = Util.next_day()
     medic.put()
     params = self.default_params
     with self.assertRaises(TimeError) as e:
         Invul.handler(medic, params)
     self.assertEqual(e.exception.message, "You cannot set invul before time {}."\
             .format(Util.utc_to_chi(medic.can_set_after).strftime("%m-%d %I:%M%p")))
     self.assertEqual(len(self.invul_queue), 0)
Example #8
0
    def test_reply_disarm_y(self):
        """ Test disarm reply y """
        later = Util.utc_to_chi(self.action.datetime + timedelta(hours=1))

        ret = Disarm.reply_handler(self.action, "y")
        self.assertEqual(1, len(ret))
        self.assertEqual(ret[0][0], "+1")
        self.assertEqual(ret[0][1], "You have been DISARM until {}".format(\
                later.strftime("%m-%d %I:%M%p")))
        self.assertEqual(self.p1a.disarm, True)
        self.assertEqual(len(self.taskqueue_stub.get_filtered_tasks(\
                queue_names='disarm')), 1)
Example #9
0
    def test_reply_disarm_y(self):
        """ Test disarm reply y """
        later = Util.utc_to_chi(self.action.datetime + timedelta(hours=1))

        ret = Disarm.reply_handler(self.action, "y")
        self.assertEqual(1, len(ret))
        self.assertEqual(ret[0][0], "+1")
        self.assertEqual(ret[0][1], "You have been DISARM until {}".format(\
                later.strftime("%m-%d %I:%M%p")))
        self.assertEqual(self.p1a.disarm, True)
        self.assertEqual(len(self.taskqueue_stub.get_filtered_tasks(\
                queue_names='disarm')), 1)
Example #10
0
 def setUp(self):
     super(TestBomb, self).setUp()
     test_dt = Util.utc_to_chi(datetime.now()) + timedelta(minutes=1)
     self.default_params = ["Here", str(test_dt.month), str(test_dt.day),\
             str(test_dt.hour), str(test_dt.minute)]
     
     action = Action()
     action.attacker = "+1"
     action.action = "BOMB"
     action.victim = "*"
     action.datetime = datetime.now()
     action.place = "Place"
     action.put()
     self.action = action
Example #11
0
def bomb_worker():
    ''' Get bomb id '''
    req_key = request.form.get('id', "")
    bomb = Bomb.get_by_id(int(req_key))

    ''' ERROR: no bomb found by id '''
    if not bomb:
        logging.error("BOMB Worker: No bomb found by key {}".format(req_key))
        raise Exception()

    ''' Bomb deprecated no action '''
    if bomb.deprecated:
        logging.info("BOMB Worker: Bomb with key {} deprecated. No explosion".format(req_key))
        return "BOMB Worker: Deprecated Bomb"

    ''' Trigger bomb '''
    logging.info("BOMB: triggered at {} UTC {} Chicago".format(
        datetime.now(),
        Util.utc_to_chi(datetime.now().replace(tzinfo=pytz.utc))))
    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

    attacker = Player.get_by_id(bomb.attacker)
    attacker.can_set_after = Util.next_day()
    attacker.put()

    bomb.trigger = True
    bomb_key = bomb.put()

    action = Action()
    action.attacker = bomb.attacker
    action.action = "BOMB"
    action.victim = "*"
    action.datetime = datetime.now()
    action.place = bomb.place
    action_key = action.put()


    response_num_list = [key.id() for key in Player.query(ndb.AND(Player.state=="ALIVE",\
            Player.invul==False) ).fetch(keys_only=True)]
    response = "{} has been bombed at {}. If you were there, [REPLY {}] Y.".format(
        action.place,
        Util.utc_to_chi(action.datetime).strftime("%m-%d %I:%M%p"),
        action_key.id())

    for response_number in response_num_list:
        logging.info("Making message {} for {} with num_list {}".format(
            response, response_number, response_num_list))

        '''Make message'''
        outgoing_message = Message(From=SERVER_NUMBER,
                                   To=response_number,
                                   Body=response)
        outgoing_message.put()

        '''Send message'''
        client.messages.create(
            to=response_number,
            from_=SERVER_NUMBER,
            body=response)

    return "Bomb triggered at {}".format(bomb.place)
Example #12
0
def invul_worker():
    ''' Get invul id'''
    req_key = request.form.get("id", "")
    inv = Invul.get_by_id(int(req_key))

    ''' No Inv found '''
    if not inv:
        logging.error("INV worker: no INV found")
        raise Exception()

    '''Inv deprecated'''
    if inv.deprecated:
        logging.info("INV Worker: Inv deprecated. No action.")
        return "INVUL Worker: Deprecated"

    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

    '''Target dead. Report back to medic'''
    logging.info(inv)
    target_num = inv.target
    logging.info(target_num)
    target = Player.get_by_id(target_num)
    medic = Player.get_by_id(inv.medic)
    logging.info(medic)
    if not target:
        logging.error("INV worker: cannot find target {}".format(target_num))
        return
    if target.state == "DEAD":
        logging.error("INV worker: Target {} has died. Cannot grant INVUL".format(target.codename))
        response = "Your INVUL target has died. Cannot grant dead people INVUL."
        msg = Message(From=SERVER_NUMBER,
                      To=inv.medic,
                      Body=response)
        msg.put()
        client.messages.create(
            to=inv.medic,
            from_=SERVER_NUMBER,
            body=response)
        return "INVUL Worker"

    '''Target alive. If INVUL not yet in effect, trigger'''
    if not inv.in_effect:
        logging.info("INVUL worker: Triggering 8 hour INVUL for target {} at {}".format(target.codename, datetime.now()))
        inv.in_effect = True
        inv_key = inv.put()
        task = taskqueue.Task(url="/invul", params={"id": inv_key.id()}, eta=inv.end_time)
        task.add(queue_name="invul")

        logging.info("Task queue okay")
        logging.info(target)
        target.invul = True
        target.put()

        logging.info("target set okay")
        logging.info(medic)
        medic.can_set_after = Util.next_day()
        medic.put()

        logging.info("medic set okay")
        response  = "You have been granted INVUL for 8 hour from {} to {}".\
                format(Util.utc_to_chi(inv.start_time).strftime("%m-%d %I:%M%p"),\
                Util.utc_to_chi(inv.end_time).strftime("%m-%d %I:%M%p"))
        msg = Message(From=SERVER_NUMBER,
                      To=inv.target,
                      Body=response)
        msg.put()
        client.messages.create(
            to=inv.target,
            from_=SERVER_NUMBER,
            body=response)
        logging.info("message set okay")
        return "INVUL Worker"
    else:
        logging.info("INVUL worker: END 8 hour INVUL for target {} at {}".format(target.codename, datetime.now()))
        inv.deprecated = True
        inv.put()
        target.invul = False
        target.put()

        response = "Your INVUL period has ended. You are no longer INVUL."
        msg = Message(From=SERVER_NUMBER,
                      To=inv.target,
                      Body=response)
        msg.put()
        client.messages.create(
            to=inv.target,
            from_=SERVER_NUMBER,
            body=response)
        return "INVUL Worker"
Example #13
0
    def handler(cls, attacker, params):
        '''Validation'''
        if attacker.state == "DEAD":
            raise MeError("DEAD")

        if attacker.role != "DEMO":
            raise MeError("not DEMO")

        if datetime.now() < attacker.can_set_after:
            raise TimeError("bomb", Util.utc_to_chi(attacker.can_set_after))

        if attacker.disarm:
            raise MeError("DISARM")

        ''' Parse place and time '''
        if len(params) < 5:
            raise CommandError("BOMB - {}".format(" ".join(params)))
        month = params.pop(0)
        day = params.pop(0)
        minute = params.pop(0)
        second = params.pop(0)
        place = " ".join(params)

        central = pytz.timezone("US/Central")
        chi_dt = datetime(2016,
                        int(month),
                        int(day),
                        int(minute),
                        int(second),
                        tzinfo=central)
        utc_dt = Util.chi_to_utc(chi_dt)
        logging.debug("CHI time: {}".format(chi_dt))
        logging.debug("UTC time: {}".format(utc_dt))

        if utc_dt < datetime.now():
            cur_time = Util.utc_to_chi(datetime.now())
            logging.error("BOMB: trying to set time {} before now {} (UTC)".format(utc_dt.isoformat(' '), datetime.now().isoformat(' ')))
            raise TimeError(chi_dt, cur_time)

        '''Make new bomb'''
        bomb = Bomb()
        bomb.attacker = attacker.key.id()
        bomb.place = place
        bomb.time = utc_dt
        bomb.trigger = False
        bomb_key = bomb.put()

        ''' Invalidate old bomb '''
        try:
            old_bomb = Bomb.get_by_id(attacker.item)
            logging.info("BOMB: invalidating old bomb with id {}".format(attacker.item))
            old_bomb.deprecated = True
            old_bomb.put()
        except:
            logging.info("BOMB: unable to invalidate old bomb")

        ''' Setting new bomb '''
        attacker.item = bomb_key.id()
        attacker.put()

        task = taskqueue.Task(url="/bomb", params={"id": bomb_key.id()}, eta=utc_dt)
        task.add(queue_name="bomb")

        logging.info("BOMB: set for {} at {}".format(utc_dt, place))

        return [(bomb.attacker, "Your bomb in {} will explode at {}".format(
            bomb.place, chi_dt.strftime("%m-%d %I:%M%p")))]
Example #14
0
    def handler(cls, attacker, params):
        '''Validation'''
        if attacker.state == "DEAD":
            raise MeError("DEAD")

        if attacker.role != "DEMO":
            raise MeError("not DEMO")

        if datetime.now() < attacker.can_set_after:
            raise TimeError("bomb", Util.utc_to_chi(attacker.can_set_after))

        if attacker.disarm:
            raise MeError("DISARM")
        ''' Parse place and time '''
        if len(params) < 5:
            raise CommandError("BOMB - {}".format(" ".join(params)))
        month = params.pop(0)
        day = params.pop(0)
        minute = params.pop(0)
        second = params.pop(0)
        place = " ".join(params)

        central = pytz.timezone("US/Central")
        chi_dt = datetime(2016,
                          int(month),
                          int(day),
                          int(minute),
                          int(second),
                          tzinfo=central)
        utc_dt = Util.chi_to_utc(chi_dt)
        logging.debug("CHI time: {}".format(chi_dt))
        logging.debug("UTC time: {}".format(utc_dt))

        if utc_dt < datetime.now():
            cur_time = Util.utc_to_chi(datetime.now())
            logging.error(
                "BOMB: trying to set time {} before now {} (UTC)".format(
                    utc_dt.isoformat(' '),
                    datetime.now().isoformat(' ')))
            raise TimeError(chi_dt, cur_time)
        '''Make new bomb'''
        bomb = Bomb()
        bomb.attacker = attacker.key.id()
        bomb.place = place
        bomb.time = utc_dt
        bomb.trigger = False
        bomb_key = bomb.put()
        ''' Invalidate old bomb '''
        try:
            old_bomb = Bomb.get_by_id(attacker.item)
            logging.info("BOMB: invalidating old bomb with id {}".format(
                attacker.item))
            old_bomb.deprecated = True
            old_bomb.put()
        except:
            logging.info("BOMB: unable to invalidate old bomb")
        ''' Setting new bomb '''
        attacker.item = bomb_key.id()
        attacker.put()

        task = taskqueue.Task(url="/bomb",
                              params={"id": bomb_key.id()},
                              eta=utc_dt)
        task.add(queue_name="bomb")

        logging.info("BOMB: set for {} at {}".format(utc_dt, place))

        return [(bomb.attacker, "Your bomb in {} will explode at {}".format(
            bomb.place, chi_dt.strftime("%m-%d %I:%M%p")))]
Example #15
0
 def setUp(self):
     super(TestInvul, self).setUp()
     test_dt = Util.utc_to_chi(datetime.now()) + timedelta(minutes=1)
     self.default_params = ["p1a", str(test_dt.month), str(test_dt.day),\
             str(test_dt.hour), str(test_dt.minute)]
Example #16
0
    def handler(cls, attacker, params):
        """ Validation """
        if len(params) != 5:
            raise CommandError("INVUL - {}".format(params))

        if attacker.state == "DEAD":
            raise MeError("DEAD")

        if attacker.role != "MEDIC":
            raise MeError("not MEDIC")

        target_codename = params.pop(0)
        target = Util.get_victim(target_codename)

        if target.team != attacker.team:
            raise TeamError

        if target.state == "DEAD":
            raise TargetError("DEAD")

        chi_start_time = datetime(year=2016, month=int(params[0]),\
                day=int(params[1]), hour=int(params[2]),\
                minute=int(params[3]))
        utc_start_time = Util.chi_to_utc(chi_start_time)
        utc_end_time = utc_start_time + timedelta(hours=8)

        if utc_start_time < datetime.now():
            raise TimeError(chi_start_time, Util.utc_to_chi(datetime.now()))

        if datetime.now() < attacker.can_set_after:
            raise TimeError("invul", Util.utc_to_chi(attacker.can_set_after))

        """ Make new Invul """
        invul = Invul()
        invul.medic = attacker.key.id()
        invul.target = target.key.id()
        invul.start_time = utc_start_time
        invul.end_time = utc_end_time

        """ Invalidate old invul """
        try:
            old_invul = Invul.get_by_id(attacker.item)
            logging.info("INVUL: invalidating old invul with id {}".\
                    format(attacker.item))
            if old_invul.in_effect or old_invul.deprecated:
                raise TimeError("invul" "midnight")
            old_invul.deprecated = True
            old_invul.put()
        except:
            logging.info("INVUL: unable to invalidate old invul")

        invul_key = invul.put()
        attacker.item = invul_key.id()
        attacker.put()

        task = taskqueue.Task(url="/invul", params={"id": invul_key.id()},\
                eta = utc_start_time)
        task.add(queue_name="invul")

        return [(invul.medic, "Invul will been set for {} from {} to {}.".\
                format(target_codename,\
                chi_start_time.strftime("%m-%d %I:%M%p"),
                Util.utc_to_chi(utc_end_time).strftime("%m-%d %I:%M%p")))]