Exemplo n.º 1
0
    def test_retrieve_invite(self):
        # let's create two invites first
        user_three = User(username='******', email='*****@*****.**')
        user_three.put()

        invite_one = Invite(to_player=self.user_one.key,
                            to_player_name=self.user_one.username,
                            from_player=self.user_two.key,
                            from_player_name=self.user_two.username)
        invite_two = Invite(to_player=self.user_one.key,
                            to_player_name=self.user_one.username,
                            from_player=user_three.key,
                            from_player_name=user_three.username)

        invite_one.put()
        invite_two.put()

        # created. Let's retrieve the invites
        resp = self.testapp.post(
            '/_ah/spi/RetrieveInviteHandler.retrieve_invite',
            params=json.dumps({"jwt_token": self.jwt_token_player_one}),
            content_type='application/json')
        resp = json.loads(resp.body)
        self.assertEqual(len(resp['invites']), 2,
                         'Two invites were not retrieved after being created')
Exemplo n.º 2
0
    def test_retrieve_rejected(self):
        # let's create two invites first
        user_three = User(username='******', email='*****@*****.**')
        user_three.put()

        invite_one = Invite(to_player=self.user_one.key,
                            to_player_name=self.user_one.username,
                            from_player=self.user_two.key,
                            from_player_name=self.user_two.username)
        invite_two = Invite(to_player=self.user_one.key,
                            to_player_name=self.user_one.username,
                            from_player=user_three.key,
                            from_player_name=user_three.username,
                            rejected=True)

        invite_one.put()
        invite_two.put()

        # created. Let's retrieve the invites
        resp = self.testapp.post(
            '/_ah/spi/RetrieveInviteHandler.retrieve_invite',
            params=json.dumps({"jwt_token": self.jwt_token_player_one}),
            content_type='application/json')
        self.assertEqual(
            len(json.loads(resp.body)), 1,
            'One invite was not retrieved after creating two and cancelling one'
        )
Exemplo n.º 3
0
def initModels(cls):
    """Initialize the models."""
    # admin
    cls.admin = User()
    cls.admin.name = "admin"
    cls.admin.email = ["admin@email"]
    cls.admin.put()

    # user
    cls.user = User()
    cls.user.name = "user"
    cls.user.email = ["user@email"]
    cls.user.put()

    # New institution
    cls.institution = Institution()
    cls.institution.name = "institution"
    cls.institution.admin = cls.admin.key
    cls.institution.members = [cls.admin.key]
    cls.institution.followers = [cls.admin.key]
    cls.institution.put()

    # update admin
    cls.admin.institutions_admin = [cls.institution.key]
    cls.admin.put()

    # New invite
    cls.invite = Invite()
    cls.invite.invitee = cls.user.email[0]
    cls.invite.admin_key = cls.admin.key
    cls.invite.sender_key = cls.admin.key
    cls.invite.sender_name = cls.admin.name
    cls.invite.status = "sent"
    cls.invite.institution_key = cls.institution.key
    cls.invite.put()

    cls.data = {
        "admin_key": cls.admin.key.urlsafe(),
        "is_request": False,
        "institution_key": cls.institution.key.urlsafe(),
        "sender_key": cls.admin.key.urlsafe(),
        "sender_name": cls.admin.name
    }

    cls.expected_invite = Invite()
    cls.expected_invite.admin_key = cls.admin.key
    cls.expected_invite.is_request = False
    cls.expected_invite.institution_key = cls.institution.key
    cls.expected_invite.sender_key = cls.admin.key
    cls.expected_invite.sender_name = cls.admin.name
Exemplo n.º 4
0
    def invite(self, sess, comment, investor, invitee_name):
        if investor.firm == 0:
            return comment.reply_wrap(message.no_firm_failure_org)

        if investor.firm_role == "":
            return comment.reply_wrap(message.not_assoc_org)

        firm = sess.query(Firm).\
            filter(Firm.id == investor.firm).\
            first()

        if not firm.private:
            return comment.reply_wrap(message.invite_not_private_failure_org)

        invitee = sess.query(Investor).\
            filter(func.lower(Investor.name) == func.lower(invitee_name)).\
            first()
        if invitee == None:
            return comment.reply_wrap(message.invite_no_user_failure_org)
        if invitee.firm != 0:
            return comment.reply_wrap(message.invite_in_firm_failure_org)

        sess.add(Invite(firm=firm.id, investor=invitee.id))

        return comment.reply_wrap(message.modify_invite(invitee, firm))
Exemplo n.º 5
0
    def execute(self):
        """
            1 - Will create the invite in database
            2 - Will insert the sender as attendee1
            3 - If is anonymous will send the invite for confirmation to the organizer
            4 - Else will post the invite to Voiceflows
        """

        invite = Invite()
        copy_over(self, invite)
        invite.put()
        index_invite(invite)

        addOrganizerCommand = self._get_organizer_attendee(invite)
        addOrganizerCommand.execute()

        if not self.user_object:
            '''is anonymous'''
            command = SendConfirmationInviteToOrganizerCommand(invite, self.host)
            command.execute()
            return invite.unique_id

        command = PostInviteToVoiceflowsCommand(invite)
        command.execute()

        return invite.unique_id
Exemplo n.º 6
0
    def test_create_getting_sender_key_from_data(self):
        """Test invite create method."""
        # test the case in which the data has the sender key and name
        invite = Invite()
        created_invite = Invite.create(self.data, invite)

        self.assertEquals(
            created_invite, self.expected_invite,
            "The created invite should be iqual to the expected one")
Exemplo n.º 7
0
def generate_invite_code(user):
    pool = string.ascii_letters + string.digits
    code = ''.join(random.choice(pool) for _ in range(32))

    invite_code = Invite(code, user.id)
    db_session.add(invite_code)
    db_session.commit()

    return code
Exemplo n.º 8
0
def invite():
    if logged_in():
        invite = Invite()
        db.session.add(invite)
        db.session.commit()
        token = invite.token
        db.session.close()
        return request.url_root + 'register?token=' + token
    return "Must be logged in to generate invite"
Exemplo n.º 9
0
    def test_create_getting_sender_key_from_invite(self):
        """Test the case in which the sender key is get from the invite."""
        self.data["sender_key"] = None
        self.data["sender_name"] = None
        invite = Invite()
        invite.admin_key = self.admin.key
        created_invite = Invite.create(self.data, invite)

        self.assertEquals(
            created_invite, self.expected_invite,
            "The created invite should be iqual to the expected one")
Exemplo n.º 10
0
def gen_invites():
    u = g.current_user

    if u.can_have_more_invites():
        invite = Invite()
        invite.generate_code()
        g.current_user.invites.append(invite)
        db_session.add(invite)
        db_session.commit()
        return jsonify(invite=invite_schema.dump(invite))
    return bad_request('UNREDEEMED')
Exemplo n.º 11
0
def invite(request):
    profile = request.user.userprofile
    invite_form = forms.InviteForm(request.POST or None,
                                   instance=Invite(inviter=profile))
    if request.method == 'POST' and invite_form.is_valid():
        invite = invite_form.save()
        invite.send(sender=profile)
        return render(request, 'phonebook/invited.html',
                      {'recipient': invite.recipient})

    return render(request, 'phonebook/invite.html',
                  {'invite_form': invite_form})
Exemplo n.º 12
0
 def post(self):
     name = self.request.get('name')
     email = self.request.get('email')
     invite_code = uuid.uuid4().hex[:invite_code_len].upper()
     while(Invite.query(Invite.code==invite_code).get()):
         invite_code = uuid.uuid4().hex[:invite_code_len].upper()
     invite = Invite(code=invite_code, name=name, email=email)
     invite.put()
     context = {
         'invite': invite,
         'invite_url': webapp2.uri_for('invite', invite_code=invite.code)
     }
     path = os.path.join(os.path.dirname(__file__), './templates/admin/index.html')
     self.response.out.write(template.render(path, context))
Exemplo n.º 13
0
def invite(request):
    profile = request.user.userprofile
    invite_form = forms.InviteForm(request.POST or None,
                                   instance=Invite(inviter=profile))
    if request.method == 'POST' and invite_form.is_valid():
        invite = invite_form.save()
        invite.send(sender=profile)
        msg = _(u"%s has been invited to Mozillians. They'll receive an email "
                "with instructions on how to join. You can "
                "invite another Mozillian if you like." % invite.recipient)
        messages.success(request, msg)
        return redirect(reverse('profile', args=[request.user.username]))

    return render(request, 'phonebook/invite.html',
                  {'invite_form': invite_form})
Exemplo n.º 14
0
    def test_accept_invite(self):
        # let's create invite first
        invite_one = Invite(to_player=self.user_one.key,
                            to_player_name=self.user_one.username,
                            from_player=self.user_two.key,
                            from_player_name=self.user_two.username)

        invite_one.put()

        resp = self.testapp.post_json(
            '/_ah/spi/CreateInviteHandler.create_invite', {
                "jwt_token": self.jwt_token_player_one,
                "player_two_key": self.user_two.key.urlsafe()
            })
        self.assertIn('200', resp.status)
Exemplo n.º 15
0
def create_invites():
    json_data = request.get_json()
    course = Course.query.filter_by(id=json_data['course_id'], owner_id=current_user.id).first()
    if course is None:
        return jsonify(error="Course not found"), 400
    users = set([c.username for c in course.users])
    invs = set([i.username for i in course.invites])
    usernames = set(json_data['usernames']) - users - invs
    many_invs = [Invite(username=u, course_id=course.id) for u in usernames]
    [db.session.add(inv) for inv in many_invs]
    db.session.commit()
    return jsonify({
        "message": "success",
        "invites": views_schemas.invite_schema.dump(many_invs)
    })
Exemplo n.º 16
0
def line_type(line):
    """    
    seperate line's msg into many type
    content: normal text
    multiline: is part of last content, because we split log by \n
    datestamp: date for following message
    invite: someone invite others into group
    join: the one was invited join group
    title: Group's name
    savedate: the date user saved log
    """
    content_r = re.match('(\d{2}:\d{2})\t(.*?)\t(.*?)', line)
    if content_r:
        time = content_r.group(1)
        name = content_r.group(2)
        text = content_r.group(3)
        content = Content(time, name, text)
        return content

    datestamp_r = re.match('^(\d{4}\/\d{2}\/\d{2})\((週.)\)', line)
    if datestamp_r:
        return ('datestamp', datestamp_r.group(1), datestamp_r.group(2))

    invite_r = re.match('(\d{2}:\d{2})\t(.*)邀請(.*)加入群組。', line)
    if invite:
        time = invite_r.group(1)
        inviter = invite_r.group(2)
        invitee = invite_r.group(3)
        invite = Invite(time, inviter, invitee)
        return invite

    join = re.match('(\d{2}:\d{2})\t(.*)加入聊天', line)
    if join:
        dic = {'time': join.group(1), 'name': join.group(2)}
        return ('join', dic)

    title = re.match('\ufeff\[LINE\] (.*)的聊天記錄', line)
    if title:
        return ('title', title.group(1))

    save_date = re.match('儲存日期:(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2})', line)
    if save_date:
        return ('save_date', save_date.group(1))

    if line.strip() == "":
        return ('empty', line)

    return ('multiline', line)
Exemplo n.º 17
0
 def test_cancel_invites(self):
     # cancel an invite please, but first we need to have one
     invite = Invite(to_player=self.user_one.key,
                     to_player_name=self.user_one.username,
                     from_player=self.user_two.key,
                     from_player_name=self.user_two.username).put()
     resp = self.testapp.post('/_ah/spi/CancelInviteHandler.cancel_invite',
                              params=json.dumps({
                                  "jwt_token":
                                  self.jwt_token_player_two,
                                  "target_user":
                                  self.user_one.key.urlsafe()
                              }),
                              content_type='application/json')
     invite = invite.get()
     self.assertIn('200', str(resp))
     self.assertTrue(invite.rejected, 'The invite was not rejected')
Exemplo n.º 18
0
def commit():
    print('进入了commit!')
    # 第一步:从前台获取表单中的邀标书编辑信息
    id = int(request.form.get('id'))
    project_id = int(request.form.get('project_id'))

    # # 时间字符串
    # timestr = request.form.get('opentime')
    # # 将其转换为时间数组
    # timeArray = time.strptime(timestr, "%Y-%m-%d %H:%M:%S")
    # # 转换为时间戳:
    # timeStamp = int(time.mktime(timeArray))
    # # 字符串转换成data
    # timeData = time.strptime(timestr, "%Y-%m-%d %H:%M:%S")
    # print('时间字符串是:%s'%timestr)
    # print('时间数组是:',timeArray)
    # print('时间戳是:%d'% timeStamp)
    # print('日期是:' , timeData)
    # opentime = timestr

    opentime = request.form.get('starttime')
    openposition = request.form.get('openposition')
    content = request.form.get('content')
    notice = request.form.get('notice')
    remarks = request.form.get('remarks')

    # 第二步:验证邀标书编号是否存在,若邀标书已存在,这不能添加,给出相应提示
    invite = Invite.query.filter(Invite.id == id).first()
    if invite:
        return '该邀标书已存在!'
    else:
        # 第三步:验证项目编号是否存在,若不存在就不能为该项目制定邀标书
        project = DeclareForm.query.filter(DeclareForm.id == project_id).first()
        if project:
            # 第四步:根据前台数据,构造邀标书对象,并将该邀标书的信息存进数据库
            invite2 = Invite(projectId=project_id, openTime=opentime, openPosition=openposition,
                            content=content,notice=notice,remarks=remarks)
            db.session.add(invite2)
            db.session.commit()
            # 第五步:添加邀标书成功,就刷新首页页面
            return redirect(url_for('index'))
        else:
            return '项目编号不存在!'
Exemplo n.º 19
0
def create():
    json_data = request.get_json()
    if not json_data:
        return jsonify({"message": "No json provided"}), 400
    try:
        data = schemas.create_course_schema.load(json_data)
    except ValidationError as err:
        return jsonify({"error": err.messages}), 422

    course = Course(name=data['name'], owner_id=current_user.id)
    db.session.add(course)
    db.session.commit()

    for user in data['invited_users']:
        db.session.add(Invite(username=user, course_id=course.id))

    db.session.commit()

    return jsonify(schemas.course_schema.dumps(course))
Exemplo n.º 20
0
    def test_send_invite_already_exists(self):
        # try to send an invite to a user that already has an invite pending please
        # start by creating the invite
        invite = Invite(to_player=self.user_one.key,
                        to_player_name=self.user_one.username,
                        from_player=self.user_two.key,
                        from_player_name=self.user_two.username)
        invite.put()

        # invite created, so let's have user_two try to send an invite to user_one
        resp = self.testapp.post('/_ah/spi/CreateInviteHandler.create_invite',
                                 params=json.dumps({
                                     "jwt_token":
                                     self.jwt_token_player_two,
                                     "player_two_key":
                                     self.user_one.key.urlsafe()
                                 }),
                                 content_type='application/json',
                                 expect_errors=True)
        self.assertIn('400', str(resp))
Exemplo n.º 21
0
    def test_cancel_invite_not_exist(self):
        # try to cancel an invite that doesn't belong to the user
        user_three = User(username='******', email='*****@*****.**')
        user_three.put()
        user_three_jwt = token.encode_jwt(
            {"user_key": user_three.key.urlsafe()})

        invite = Invite(to_player=self.user_one.key,
                        to_player_name=self.user_one.username,
                        from_player=self.user_two.key,
                        from_player_name=self.user_two.username).put()
        resp = self.testapp.post('/_ah/spi/CancelInviteHandler.cancel_invite',
                                 params=json.dumps({
                                     "jwt_token":
                                     user_three_jwt,
                                     "target_user":
                                     self.user_one.key.urlsafe()
                                 }),
                                 content_type='application/json',
                                 expect_errors=True)
        self.assertIn('400', str(resp))
Exemplo n.º 22
0
    def create_invite(self, request):
        """
        JWT required. Provided the user does not have an active game with the provided player two, creates
        an invite for player two. If player two has already invited the user to play a game, accepts the
        invite and creates a game for them.

        If a game is created, the user will be able to retrieve it from game endpoint and begin playing.
        """
        player_two_key = request.player_two_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key')).get()
            # grab player two please
            player_two = Key(urlsafe=player_two_key).get()
        except TypeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException('key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn')

        if player_two is None:
            raise endpoints.BadRequestException('Player does not exist')

        # awesome we have player one and two
        game = Game.query(
            Game.player_one == user.key,
            Game.player_two == player_two.key,
            Game.player_one_completed == False,
            Game.player_two_completed == False).get()

        if game is None:
            game = Game.query(Game.player_one == player_two.key,
                              Game.player_two == user.key,
                              Game.player_one_completed == False,
                              Game.player_two_completed == False).get()

        # if a game exists between these users, they need to finish it first please
        if game is not None:
            # not entirely certain what to set here, as the request wasn't necessarily wrong, but the
            # user already has a game with player_two
            raise endpoints.BadRequestException("An existing game must be finished before starting another one")

        # let's check for an existing invite between these players
        invite = Invite.query(
            Invite.from_player == user.key,
            Invite.to_player == player_two.key,
            Invite.accepted == False,
            Invite.rejected == False
        ).get()

        if invite is not None:
            raise endpoints.BadRequestException(
                "A pending invite must be accepted or declined before creating another one")

        invite = Invite.query(
            Invite.from_player == player_two.key,
            Invite.to_player == user.key,
            Invite.accepted == False,
            Invite.rejected == False
        ).get()

        if invite is not None:
            # awesome! the inviter already has an invitation from the invitee.
            # start a game, and create the turncards for each player
            try:
                game = Game(
                    player_one=player_two.key,
                    player_one_name=player_two.username,
                    player_two=user.key,
                    player_two_name=user.username
                )
                game.put()
                player_one_turncard = TurnCard(
                    owner=player_two.key,
                    game=game.key
                )
                player_two_turncard = TurnCard(
                    owner=user.key,
                    game=game.key
                )
                player_one_turncard.put()
                player_two_turncard.put()

                return CreateInviteResponseForm(
                    game_key=game.key.urlsafe(),
                    game=game.to_form()
                )

            except Exception as e:
                # print e.message
                raise endpoints.InternalServerErrorException('An error occurred while attempting to create a game')

        # alright there are no invites between these players yet so let's make one
        try:
            invite = Invite(
                from_player=user.key,
                from_player_name=user.username,
                to_player=player_two.key,
                to_player_name=player_two.username
            )
            invite.put()
            return CreateInviteResponseForm()
        except:
            raise endpoints.InternalServerErrorException('An error occurred while attempting to create an invite')
Exemplo n.º 23
0
def create_invite(code, org_name):
    org = Organization.query(Organization.name == org_name).get()
    i = Invite(org=org.key, code=code)
    i.put()