Ejemplo n.º 1
0
def signup_begin(request):
    context = RequestContext(request)

    if not settings.SELF_REGISTER:
        return redirect('account_login')

    if request.POST:
        form = VPNBeginSignupForm(request.POST)
    else:
        form = VPNBeginSignupForm()

    success = False
    
    if form.is_valid():
        token = get_random_string(length=50)
            
        invite = Invite(token=token, email=form.cleaned_data['email'])
        invite.save()
        
        url = request.build_absolute_uri(reverse('account_signup', args=[token]))
        
        message = render_to_string("account/signupmsg.txt", {'url' : url}, context_instance=context)
        
        send_branded_email("Inscription", message, form.cleaned_data['email'])
        
        success = True
        
    return render(request, "registration/begin.html", {'form' : form, 'success' : success})
Ejemplo n.º 2
0
    def post(self):
        email = self.request.get('email')

        error = check_email_valid(email)
        if not error and Guest.query(Guest.email == email).get():
            error = u"Данный Email уже существует"
        if error:
            invite = Invite.query(Invite.url == self.request.path[1:]).get()
            template_values = {
                'error': error,
                'title': invite.title,
                'url': invite.url,
            }
            template = JINJA_ENVIRONMENT.get_template('invite.html')
            self.response.write(template.render(template_values))
            return

        path = self.request.get('url')
        invite = Invite.query(Invite.url == path).get()
        if invite.count == invite.users_count:
            self.redirect('/')
            return
        invite.users_count += 1
        invite.put()

        token = hashlib.md5(u'%s-%s' % (datetime.now(), email)).hexdigest()
        guest = Guest(email=email,
                      token=token,
                      date=datetime.now(),
                      invite=invite)
        guest.put()
        self.response.set_cookie('token', token, max_age=3600)
        template = JINJA_ENVIRONMENT.get_template('sign.html')
        self.response.write(template.render())
Ejemplo n.º 3
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
Ejemplo n.º 4
0
 def post(self):
     title_invite = self.request.get('title')
     try:
         count_invite = int(self.request.get('count'))
     except ValueError:
         count_invite = 5
     url_invite = hashlib.md5(u'%s-%s' % (datetime.now(), count_invite)).hexdigest()
     invite = Invite(title=title_invite,
                     url=url_invite,
                     count=count_invite)
     invite.put()
     self.redirect('/invite_view')
Ejemplo n.º 5
0
    def execute(self):
        invite_attendee = None
        invite_attendee = InviteAttendee(
            unique_id=guid()
        )

        invite_attendee.name = self.name
        invite_attendee.email = self.email
        if self.status:
            invite_attendee.attendee_status = self.status
        invite_attendee.phone = self.phone

        if self.contact_unique_id:
            contact = Contact.get_by_unique_id(
                self.contact_unique_id
            )
            if contact:
                invite_attendee.contact = contact.key

        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_unique_id)
        invite_attendee.invite = self.invite.key

        invite_attendee.is_organizer = self.is_organizer

        if self.user:
            UpdateUserOnAttendeesCommand.update_user_on_attendee(self.user, invite_attendee)
        elif invite_attendee.email: # We can only correlate by email now
            user = self.user_from_email(invite_attendee.email)
            if user:
                UpdateUserOnAttendeesCommand.update_user_on_attendee(user, invite_attendee)

        invite_attendee.put()
        return invite_attendee.unique_id
Ejemplo n.º 6
0
    def get(self, invite_urlsafe):
        """Get the invite whose key is invite_urlsafe."""
        invite_key = ndb.Key(urlsafe=invite_urlsafe)
        invite = Invite.get_by_id(invite_key.id())
        invite = invite.make()

        self.response.write(json.dumps(invite))
Ejemplo n.º 7
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))
Ejemplo n.º 8
0
    def execute(self):
        invite_attendee = None
        if self.invite_attendee_id:
            invite_attendee = InviteAttendee.get_by_unique_id(
                self.invite_attendee_id
            )

        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite is None:
            raise InviteNotFoundException()

        author = None
        if invite_attendee is not None:
            author = invite_attendee.name or invite_attendee.email or invite_attendee.phone

        if invite.comments is None:
            invite.comments = []

        comment = Comment()
        comment.author = author
        comment.comment = self.comment
        comment.commented_on = datetime.datetime.now()
        invite.comments.append(comment)
        invite.put()

        return comment
Ejemplo n.º 9
0
    def execute(self):
        invite_attendee = None
        if self.invite_attendee_id:
            invite_attendee = InviteAttendee.get_by_unique_id(
                self.invite_attendee_id)

        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite is None:
            raise InviteNotFoundException()

        author = None
        if invite_attendee is not None:
            author = invite_attendee.name or invite_attendee.email or invite_attendee.phone

        if invite.comments is None:
            invite.comments = []

        comment = Comment()
        comment.author = author
        comment.comment = self.comment
        comment.commented_on = datetime.datetime.now()
        invite.comments.append(comment)
        invite.put()

        return comment
Ejemplo n.º 10
0
    def query(self):
        """
        Returns a list of comments from the invite
        [
            {
                'author':   '',
                'comment':  '',
                'on':       ''
            }
        ]
        """
        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite.comments is None:
            invite.comments = []

        def date_compare(x, y):
            if x.commented_on > y.commented_on:
                return -1
            return 1

        return [{
            'unique_id':
            c.unique_id,
            'author':
            c.author,
            'comment':
            c.comment,
            'on':
            convert_to_user_date(c.commented_on,
                                 invite.utc_offset).strftime("%Y-%m-%d %H:%M")
        } for c in sorted(invite.comments, cmp=date_compare)]
Ejemplo n.º 11
0
def create_user(auth, email, name, password, invite_code):
    """Creates a new user and assigns a OAuth consumer key/secret"""
    key, secret = create_consumer()
    
    invite = Invite.query(Invite.code==invite_code, Invite.is_used==False).get()
    if not invite:
        raise UserCreationError("Invalid invite code: %s" % invite_code)
        
    success, info = auth.store.user_model.create_user(
        legit_auth_id(email),
        unique_properties=['email', 'consumer_key', 'consumer_secret'],
        email=email,
        name=name,
        org=invite.org,
        invite_code=invite.code,     
        permissions=INITIAL_PERMISSIONS,           
        password_raw=password,
        consumer_key=key,
        consumer_secret=secret)
        
    if not success:
        error_msg = "That email is already in use." if 'email' in info else "Something has gone horrible wrong. Email Rob, he probably messed up."
        raise UserCreationError(error_msg)
    else:
        invite.is_used = True
        invite.put()
        
    return info
Ejemplo n.º 12
0
    def query(self):
        """
        Returns a list of comments from the invite
        [
            {
                'author':   '',
                'comment':  '',
                'on':       ''
            }
        ]
        """
        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite.comments is None:
            invite.comments = []

        def date_compare(x, y):
            if x.commented_on > y.commented_on:
                return -1
            return 1

        return [
            {
                'unique_id': c.unique_id,
                'author':   c.author,
                'comment':  c.comment,
                'on':       convert_to_user_date(
                                c.commented_on,
                                invite.utc_offset
                            ).strftime("%Y-%m-%d %H:%M")
            } for c in sorted(invite.comments, cmp=date_compare)
        ]
Ejemplo n.º 13
0
def invite_management():
    form = CreateInviteForm()
    existing_invites = Invite.query().fetch(100)
    
    return render_template("admin/invites.html",
                            existing_invites=existing_invites,
                            form=form)
Ejemplo n.º 14
0
 def confirm(self, confirmation_id):
     #we are using the confirmation_id as the invite_id for now
     invite = Invite.get_by_unique_id(confirmation_id)
     if not invite:
         raise Exception("We couldn't find the invite. Check if your link is valid.")
     command = PostInviteToVoiceflowsCommand(invite)
     command.execute()
     return self.redirect('/invite/' + invite.unique_id + '/edit')
Ejemplo n.º 15
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')
Ejemplo n.º 16
0
def email_invites():
    def sendmail(a):
        try:
            utils.sendmail_voterid_pending(a)
        except Exception:
            logger.error("failed to send email to %s", a)
    agents = Invite.find_all()    
    pool = ThreadPool(20)    
    pool.map(sendmail, agents)
Ejemplo n.º 17
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
Ejemplo n.º 18
0
    def execute(self):
        image = Image()
        image.image_key = self.image_key
        image.put()

        invite = Invite.get_by_unique_id(self.unique_id)
        invite.poster_picture = image.key
        invite.put()
        return invite.poster_picture.urlsafe()
Ejemplo n.º 19
0
 def confirm(self, confirmation_id):
     #we are using the confirmation_id as the invite_id for now
     invite = Invite.get_by_unique_id(confirmation_id)
     if not invite:
         raise Exception(
             "We couldn't find the invite. Check if your link is valid.")
     command = PostInviteToVoiceflowsCommand(invite)
     command.execute()
     return self.redirect('/invite/' + invite.unique_id + '/edit')
Ejemplo n.º 20
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"
Ejemplo n.º 21
0
def getSentInvitations(institution_key):
    """Query that return list of invites for this user."""
    invites = []

    queryInvites = Invite.query(Invite.institution_key == institution_key)

    invites = [invite.make() for invite in queryInvites]

    return invites
Ejemplo n.º 22
0
Archivo: index.py Proyecto: xplot/imeet
    def _get_invite_model(self, invite_id):
        """
            Get the invite by id
            TODO: Think about the location of this function.
        """
        invite_entity = Invite.get_by_unique_id(invite_id)

        if invite_entity is None:
            raise Exception("Invite not found with id: %s" % invite_id)

        return InviteModel(invite_entity)
Ejemplo n.º 23
0
    def execute(self):
        invite = Invite.get_by_unique_id(self.unique_id)

        if invite.start < datetime.now():
            raise InviteCannotBeEditedException(
                "This invite is in the past it cannot be edited anymore")

        copy_over(self, invite)
        invite.put()
        index_invite(invite)
        return invite.unique_id
Ejemplo n.º 24
0
Archivo: index.py Proyecto: xplot/imeet
    def _get_invite_model(self, invite_id):
        """
            Get the invite by id
            TODO: Think about the location of this function.
        """
        invite_entity = Invite.get_by_unique_id(invite_id)

        if invite_entity is None:
            raise Exception("Invite not found with id: %s" % invite_id)

        return InviteModel(invite_entity)
Ejemplo n.º 25
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))
Ejemplo n.º 26
0
    def execute(self):
        invite = Invite.get_by_unique_id(self.unique_id)

        if invite.start < datetime.now():
            raise InviteCannotBeEditedException(
                "This invite is in the past it cannot be edited anymore"
            )

        copy_over(self, invite)
        invite.put()
        index_invite(invite)
        return invite.unique_id
Ejemplo n.º 27
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})
Ejemplo n.º 28
0
Archivo: index.py Proyecto: xplot/imeet
    def view_invite(self, invite_id, invite_attendee_id=None):
        if not invite_id:
            return self.redirect_to('home')

        invite = Invite.get_by_unique_id(invite_id)
        invite_query = query.CompleteInviteQuery(invite=invite)
        invite_attendee = self._try_to_get_attendee(invite, invite_attendee_id)

        return self.render_template(
            'invite.html',
            invite=json.dumps(invite_query.query(), cls=DateTimeEncoder),
            invite_attendee=json.dumps(invite_attendee, cls=DateTimeEncoder),
        )
Ejemplo n.º 29
0
Archivo: index.py Proyecto: xplot/imeet
    def view_invite(self, invite_id, invite_attendee_id=None):
        if not invite_id:
            return self.redirect_to('home')

        invite = Invite.get_by_unique_id(invite_id)
        invite_query = query.CompleteInviteQuery(invite=invite)
        invite_attendee = self._try_to_get_attendee(invite, invite_attendee_id)

        return self.render_template(
            'invite.html',
            invite=json.dumps(invite_query.query(), cls=DateTimeEncoder),
            invite_attendee=json.dumps(invite_attendee, cls=DateTimeEncoder),
        )
Ejemplo n.º 30
0
def get_invites(user_email):
    """Query that return list of invites for this user."""
    invites = []

    queryInvites = Invite.query(Invite.invitee.IN(user_email),
                                Invite.status == 'sent')

    invites = [
        invite.make() if invite.institution_key.get().state == "active" else ''
        for invite in queryInvites
    ]

    return invites
Ejemplo n.º 31
0
    def execute(self):
        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite.start < datetime.now():
            raise InviteCannotBeEditedException(
                "This invite is in the past it cannot be edited anymore")

        bulk_ids = []
        if self.commands:
            for command in self.commands:
                bulk_ids.append(command.execute())

        return bulk_ids
Ejemplo n.º 32
0
    def query(self):
        """
            Returns a list of invites from the user
            1 - Can be filtered by search_term
            2 - Will be ordered according to date Descending
        """
        result = []

        invite_attendees_group = self.get_invites_grouped_by_attendee()
        if not invite_attendees_group:
            return []

        all_invites = Invite.query(Invite.key.IN(
            invite_attendees_group.keys())).order(-Invite.start).fetch()

        result = []
        for invite in all_invites:
            if self.search_term and self.search_term.lower(
            ) not in invite.title.lower():
                continue

            invite_attendee = invite_attendees_group[invite.key]

            result.append({
                'unique_id':
                invite.unique_id,
                'title':
                invite.title,
                'start':
                convert_to_user_date(
                    invite.start,
                    invite.utc_offset).strftime("%Y-%m-%d %H:%M"),
                'end':
                convert_to_user_date(
                    invite.end, invite.utc_offset).strftime("%Y-%m-%d %H:%M")
                if invite.end is not None else '',
                'poster_image_id':
                invite.poster_picture.urlsafe()
                if invite.poster_picture else None,
                'confirmed':
                0,
                'organizer':
                invite.user.id() if invite.user else None,
                'invite_attendee_id':
                invite_attendee.unique_id,
                'invite_attendee_role':
                invite_attendee.attendee_status,
                'response_on':
                invite_attendee.last_response_on
            })
        return result
Ejemplo n.º 33
0
 def post(self):
   # posted a filled out reg form
   # create the user,
   # and send an email verification including token to the new user
   email = self.request.get('email').lower()
   name = self.request.get('name')
   password = self.request.get('password')
   last_name = self.request.get('lastname')
   unique_properties = ['email_address']
   logging.info("register,POST email=%s"%email)
   user_data = self.user_model.create_user(
     email,
     unique_properties,
     email_address=email,
     name=name,
     password_raw=password,
     last_name=last_name,
     verified=False)
   if not user_data[0]:  # user_data is a tuple
     logging.warning("register,POST Duplicate %s"%email)
     self.render_template(
       'signup.html', {"message": "That userId is already registered", })
     return
   user = user_data[1]
   user_id = user.get_id()
   token = self.user_model.create_signup_token(user_id)
   invite_token = self.request.params['invite_token'] if \
     'invite' in self.request.params \
     else "none"
   inviter = Invite.checkInviteToken(invite_token)
   if inviter:
      passwordVerificationHandler.handle_verification(self,user_id,token,"v",invite_token)
   else:
       verification_url = self.uri_for('verification', type='v', user_id=user_id,
                                       signup_token=token, _full=True)
       verification_url += "&invite_token=" + str(invite_token)
       logging.info("register,POST emailing")
       mail_wrapper.send_mail(
         sender=config['system_email'],
         to=[email, '*****@*****.**'],
         subject="Rayv Registration",
         body='Click on this link to verify your address and '
              'complete the sign-up process \n'+
               verification_url
       )
       logging.info('Verification email sent to %s [%s] [%s]'%(email,verification_url, invite_token))
       params = {
         'email':email,
         'password':password
       }
       self.render_template('signup-verify.html', params)
Ejemplo n.º 34
0
    def cancel_invite(self, request):
        """
        JWT required. Cancel the invite associated with the user
        """
        target_user = request.target_user
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
        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 target_user is None or target_user is '':
            raise endpoints.BadRequestException('The target user was not provided')

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

        if invite is None:
            invite = Invite.query(Invite.to_player == user,
                                  Invite.rejected == False,
                                  Invite.accepted == False).get()

        if invite is None:
            raise endpoints.BadRequestException('No pending invites exist for these users')

        # let's cancel the invite
        try:
            invite.rejected = True
            invite.put()
            return message_types.VoidMessage()
        except:
            raise endpoints.InternalServerErrorException('An error occurred while attempting to cancel the invite')
Ejemplo n.º 35
0
    def execute(self):
        invite = Invite.get_by_unique_id(self.invite_unique_id)

        if invite.start < datetime.now():
            raise InviteCannotBeEditedException(
                "This invite is in the past it cannot be edited anymore"
            )

        bulk_ids = []
        if self.commands:
            for command in self.commands:
                bulk_ids.append(command.execute())

        return bulk_ids
Ejemplo n.º 36
0
    def get(self):
        if not users.is_current_user_admin():
            self.error(404)
            self.response.write("<html><head><title>404 Not Found</title></head><body><h1>"
                                "404 Not Found</h1>The resource could not be found.<br /><br /></body></html>")
            return

        sort_tag = self.request.get('sort')
        invite_order = sort_tag_dict[sort_tag]
        template_values = {
            'invites': Invite.query().order(invite_order),
        }
        template = JINJA_ENVIRONMENT.get_template('invites_list.html')
        self.response.write(template.render(template_values))
Ejemplo n.º 37
0
Archivo: index.py Proyecto: xplot/imeet
    def _edit_invite(self, invite_id=None, invite_attendee_id=None):
        """Get the full invite, with contacts and responses"""
        if not invite_id:
            return self.redirect_to('home')

        invite = Invite.get_by_unique_id(invite_id)
        invite_query = query.CompleteInviteQuery(invite=invite)
        invite_attendee = self._try_to_get_attendee(invite, invite_attendee_id)

        return self.render_template(
            'invite.html',
            edit='True',
            invite=json.dumps(invite_query.query(), cls=DateTimeEncoder),
            invite_attendee=json.dumps(invite_attendee, cls=DateTimeEncoder) if invite_attendee else None,
        )
Ejemplo n.º 38
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})
Ejemplo n.º 39
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)
    })
Ejemplo n.º 40
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)
Ejemplo n.º 41
0
 def post(self):
   user_email = self.request.get('email').lower()
   if not re.match('[^@]+@[^@]+\.[^@]+',user_email):
     self.response.out.write("BAD EMAIL")
     return
   logging.info("emailInviteFriend "+user_email.lower())
   token = Invite.getInviteToken(self.user_id)
   uri = self.uri_for('register',type='i', invite_token=token, _full=True)
   msg = "Hi,\n I'd like to share my favourite eateries with you using the Taste5 app, "+\
   "Click this link to join for free!\n\n"+uri+"\n\n"+self.user.screen_name
   mail_wrapper.send_mail(sender=settings.config['system_email'],
                  to=user_email,
                  subject="Share my list of places to eat!",
                  body=msg)
   logging.info("Email invite sent to %s by %s"%(user_email,self.user_id))
   self.response.out.write("OK")
Ejemplo n.º 42
0
    def execute(self):
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_unique_id)
        invite_attendees = self.invite.get_attendees()

        if self.invite.start < datetime.now():
            raise Exception("Invite is in the past, it cannot be broadcasted")

        if not invite_attendees:
            raise Exception("The invite has no attendees")

        bulk = BulkNotifyAttendeesCommand(
            invite=self.invite,
            attendees_unique_ids=[x.unique_id for x in self.invite.get_attendees()]
        )
        bulk.execute()
Ejemplo n.º 43
0
Archivo: index.py Proyecto: xplot/imeet
    def _edit_invite(self, invite_id=None, invite_attendee_id=None):
        """Get the full invite, with contacts and responses"""
        if not invite_id:
            return self.redirect_to('home')

        invite = Invite.get_by_unique_id(invite_id)
        invite_query = query.CompleteInviteQuery(invite=invite)
        invite_attendee = self._try_to_get_attendee(invite, invite_attendee_id)

        return self.render_template(
            'invite.html',
            edit='True',
            invite=json.dumps(invite_query.query(), cls=DateTimeEncoder),
            invite_attendee=json.dumps(invite_attendee, cls=DateTimeEncoder)
            if invite_attendee else None,
        )
Ejemplo n.º 44
0
    def execute(self):
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_unique_id)
        invite_attendees = self.invite.get_attendees()

        if self.invite.start < datetime.now():
            raise Exception("Invite is in the past, it cannot be broadcasted")

        if not invite_attendees:
            raise Exception("The invite has no attendees")

        bulk = BulkNotifyAttendeesCommand(
            invite=self.invite,
            attendees_unique_ids=[
                x.unique_id for x in self.invite.get_attendees()
            ])
        bulk.execute()
Ejemplo n.º 45
0
    def test_send_invites(self):
        # create the invite
        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()
            })
        # verify the invite was sent to user_two
        resp = self.testapp.post_json(
            '/_ah/spi/RetrieveInviteHandler.retrieve_invite',
            {"jwt_token": self.jwt_token_player_two})

        data = json.loads(resp.body)
        self.assertEqual(len(data['invites']), 1, 'One invite was not created')
        invite = Invite.query(Invite.from_player == self.user_one.key,
                              Invite.to_player == self.user_two.key).get()
        self.assertIsNotNone(invite)
Ejemplo n.º 46
0
 def get(self, invite_code):
     invite = Invite.query(Invite.code==invite_code).get()
     if invite:
         invite.last_viewed = datetime.now()
         invite.viewed += 1
         invite.put()
         path = os.path.join(os.path.dirname(__file__), './templates/invite.html')
         context = {
             'invite': invite,
             'rsvped': invite.accepted is not None,
             'accepted': invite.accepted is None or invite.accepted,
             'rejected': invite.accepted is False,
         }
         self.response.out.write(template.render(path, context))
     else:
         self.response.set_status(404)
         self.response.write('not found')
Ejemplo n.º 47
0
    def query(self):
        """
        Returns an Attendee on the Invite containing the parameter user

        """
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_id)

        invite_attendee = InviteAttendee.query(ndb.AND(
            InviteAttendee.user == self.user.key,
            InviteAttendee.invite == self.invite.key,
        )).get()

        if not invite_attendee:
            return None

        return InviteAttendeeQuery(invite_attendee).query()
Ejemplo n.º 48
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,
        "invitee": cls.user.email[0],
        "suggestion_institution_name": "new Institution"
    }
Ejemplo n.º 49
0
    def query(self):
        """
        Returns an Attendee on the Invite containing the parameter user

        """
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_id)

        invite_attendee = InviteAttendee.query(
            ndb.AND(
                InviteAttendee.user == self.user.key,
                InviteAttendee.invite == self.invite.key,
            )).get()

        if not invite_attendee:
            return None

        return InviteAttendeeQuery(invite_attendee).query()
Ejemplo n.º 50
0
    def add_volunteer(self, row, ac, batch, as_invite):
        if not row.name:
            return

        if row.place:
            key = ac.key + "/" + row.place.split("-")[0].strip()
            place = Place.find(key)
            if not place:
                return
        else:
            place = ac
        if row.email and place.find_volunteer(email=row.email, phone=None, role=row.role):
            logger.warn("Already found a vol with same email and role. Ignoring this %s", row)
            return
        if row.phone and place.find_volunteer(email=None, phone=row.phone, role=row.role):
            logger.warn("Already found a vol with same phone number and role. Ignoring this %s", row)
            return
        if not row.email and not row.phone:
            logger.warn("No email/phone number specified. Ignoring this %s", row)
            return

        if as_invite:
            if not row.email:
                logger.warn("Can't add invite as no email provided. Ignoring this %s", row)
                return
            if Invite.find_by_email(row.email):
                logger.warn("Already found an invite with the same email. Ignoring this %s", row)
                return

            place.add_invite(       
                name=row.name, 
                phone=row.phone, 
                email=row.email, 
                batch=batch)
        else:
            place.add_volunteer(
                name=row.name, 
                phone=row.phone, 
                email=row.email, 
                voterid=row.voterid, 
                role=row.role,
                notes=batch)
        return True
Ejemplo n.º 51
0
    def query(self):
        """
            Returns a list of invites from the user
            1 - Can be filtered by search_term
            2 - Will be ordered according to date Descending
        """
        result = []

        invite_attendees_group = self.get_invites_grouped_by_attendee()
        if not invite_attendees_group:
            return []

        all_invites = Invite.query(
            Invite.key.IN(invite_attendees_group.keys())
        ).order(-Invite.start).fetch()

        result = []
        for invite in all_invites:
            if self.search_term and self.search_term.lower() not in invite.title.lower():
                continue

            invite_attendee = invite_attendees_group[invite.key]

            result.append({
                'unique_id': invite.unique_id,
                'title':     invite.title,
                'start':     convert_to_user_date(
                    invite.start,
                    invite.utc_offset
                ).strftime("%Y-%m-%d %H:%M"),
                'end':       convert_to_user_date(
                    invite.end,
                    invite.utc_offset
                ).strftime("%Y-%m-%d %H:%M") if invite.end is not None else '',
                'poster_image_id': invite.poster_picture.urlsafe() if invite.poster_picture else None,
                'confirmed': 0,
                'organizer': invite.user.id() if invite.user else None,

                'invite_attendee_id': invite_attendee.unique_id,
                'invite_attendee_role': invite_attendee.attendee_status,
                'response_on':  invite_attendee.last_response_on
            })
        return result
Ejemplo n.º 52
0
    def get(self):
        token = self.request.cookies.get('token')
        if token:
            template = JINJA_ENVIRONMENT.get_template('sign.html')
            self.response.write(template.render())
            return

        path = self.request.path[1:]
        invite = Invite.query(Invite.url == path).get()
        if invite.count == invite.users_count:
            self.redirect('/')
            return

        invite.views_count += 1
        invite.put()
        template_values = {
            'title': invite.title,
            'url': invite.url,
        }
        template = JINJA_ENVIRONMENT.get_template('invite.html')
        self.response.write(template.render(template_values))
Ejemplo n.º 53
0
    def query(self):
        """
        Returns the invite organizer minimally formatted
        This is a valid data-format:
            {
                'unique_id':  '',
                'name': u'',
                'phone':
                'email': '',
                'status':,
                'is_organizer':,
            }
        """
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_unique_id)

        invite_attendee = InviteAttendee.query(
            ndb.AND(
                InviteAttendee.invite == self.invite.key,
                InviteAttendee.is_organizer == True
            )
        ).get()

        if not invite_attendee:
            return None

        attendee = {
            'unique_id': invite_attendee.unique_id,
            'invite_attendee_id': invite_attendee.unique_id,
            'name': invite_attendee.name,
            'phone': invite_attendee.phone,
            'email': invite_attendee.email,
            'user_id': invite_attendee.user.id() if invite_attendee.user else None,
            'status': AttendeeStatus.ORGANIZER,
            'notifications': [],
            'acknowledges': []
        }

        return attendee
    def execute(self):
        invite_attendee = None
        if self.invite_attendee_id:
            invite_attendee = InviteAttendee.get_by_unique_id(self.invite_attendee_id)
        else:
            invite_attendee = InviteAttendee(
                unique_id=guid()
            )

        invite_attendee.name = self.name
        invite_attendee.email = self.email
        invite_attendee.phone = self.phone

        contact = None

        if self.user and self.unique_id:
            contact = Contact.get_by_unique_id(
                self.unique_id
            )

        elif self.user:
            contact = Contact(
                unique_id=guid(),
                user=self.user
            )

        # Here we update the contact with the appropiate Data
        if contact:
            invite_attendee.contact = contact.key
            contact.name = self.name
            contact.email = self.email
            contact.phone = self.phone
            contact.put()

        invite = Invite.get_by_unique_id(self.invite_id)
        invite_attendee.invite = invite.key

        invite_attendee.put()
        return invite_attendee.unique_id
Ejemplo n.º 55
0
    def execute(self):
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_unique_id)

        invite_attendees = InviteAttendee.query(
            InviteAttendee.unique_id.IN(self.attendees_unique_ids)
        ).fetch()

        body = {
            'invite_unique_id': self.invite.unique_id,
            'uniquecall_id': guid(),
            'attendees': []
        }

        bulk_notifications = []

        for invite_attendee in invite_attendees:

            if self._check_if_skip_attendee(invite_attendee):
                continue

            bulk_notifications += self.create_notification_records(invite_attendee)

            body['attendees'].append(NotifyAttendeeQuery(
                invite_attendee
            ).query())

        group_id = EventQueue.get_group_id(self.invite.unique_id)
        EventQueue.push_event(
            endpoint=config.get('api_url') + "/attendees",
            headers=get_voiceflows_headers(),
            payload=body,
            group_id=group_id, #Same Group as Invite Creation
            priority=1 #Lower priority than Invite Creation
        )

        ndb.put_multi(bulk_notifications)
Ejemplo n.º 56
0
    def query(self):
        """
        Returns a list of Invite Attendee Notifications
        This is a valid data-format:
        [
            {
                'invite_attendee_id':  '',
                'name': u'',
                'phone':
                'email': '',
                'status': '',
                'response_on':'',
                'notified': True|False
            }
        ]
        """
        if not self.invite:
            self.invite = Invite.get_by_unique_id(self.invite_unique_id)

        if not self.invite:
            raise InviteNotFoundException()

        invite_attendee_notifications = InviteAttendeeNotification.get_by_invite(
            self.invite
        )

        result = []
        for invite_attendee in self.invite.get_attendees():
            invite_attendee_query = InviteAttendeeQuery(invite_attendee).query()
            invite_attendee_query['notified'] = self._is_notified(
                invite_attendee,
                invite_attendee_notifications
            )
            result.append(invite_attendee_query)

        return result
Ejemplo n.º 57
0
    def post(self):
        email = self.request.get('email')
        pattern = re.compile("[^@]+@[^@]+\.[^@]+")
        if not pattern.match(email):
            self.redirect('/invite_view')
            return

        path = self.request.get('url')
        invite = Invite.query(Invite.url == path).get()
        if invite.count == invite.users_count:
            self.redirect('/')
            return
        invite.users_count += 1
        invite.put()

        token = hashlib.md5(u'%s-%s' % (datetime.now(), email)).hexdigest()
        guest = Guest(email=email,
                      token=token,
                      date=datetime.now(),
                      invite=invite)
        guest.put()
        self.response.set_cookie('token', token, max_age=3600)
        template = JINJA_ENVIRONMENT.get_template('sign.html')
        self.response.write(template.render())
Ejemplo n.º 58
0
 def view_confirmation(self, invite_id):
     invite = Invite.get_by_unique_id(invite_id)
     if not invite.organizer_email:
         raise Exception("There's no need for a confirmation email for this invite")
     return self.render_template("invite_confirmation.html", organizer_email=invite.organizer_email)
Ejemplo n.º 59
0
def account(request):
    context = RequestContext(request)
    
    passwordform = PasswordChangeForm(request.user)
    profileform = VPNProfileForm(instance=request.user)
    emailform = VPNEmailChangeForm(instance=request.user)
    inviteform = VPNInviteForm()
    
    success = False
    success_message = None
    
    if request.method == 'POST' and request.POST.has_key("password"):
        passwordform = PasswordChangeForm(request.user, request.POST)
        
        if passwordform.is_valid():
            request.user.set_password(passwordform.cleaned_data['new_password1'])
            request.user.save()
            success = True
    
    if request.method == 'POST' and request.POST.has_key("profile"):    
        profileform = VPNProfileForm(request.POST, instance=request.user)
        
        if profileform.is_valid():
            profileform.save()
            success = True
    
    if request.method == 'POST' and request.POST.has_key("emailchange"):
        emailform = VPNEmailChangeForm(request.POST, instance=request.user)
        
        if emailform.is_valid():
            token = get_random_string(length=50)
            validation = MailValidation(user=request.user, token=token, email=emailform.cleaned_data['email'])
            validation.save()
            
            url = request.build_absolute_uri(reverse('account_mailvalidation', args=[token]))
            message = render_to_string("account/mailvalidation.txt", {'url' : url}, context_instance=context)
            send_branded_email("Validation d'adresse e-mail", message, emailform.cleaned_data['email'])
            
            success = True
            success_message = "Un email vous a été envoyé contenant un lien permettant de valider votre nouvelle adresse."

    if request.method == 'POST' and request.POST.has_key('invitechange'):
        inviteform = VPNInviteForm(request.POST)
        if inviteform.is_valid():
            token = get_random_string(length=50)

            invite = Invite(token=token, email=inviteform.cleaned_data['email'])
            invite.save()

            url = request.build_absolute_uri(reverse('account_signup', args=[token]))

            message = render_to_string("account/invitemsg.txt", {'url' : url}, context_instance=context)

            send_branded_email("Invitation", message, inviteform.cleaned_data['email'])

            success = True
            success_message = "L'invitation a bien été envoyée."

    return render(request, "account/account.html",
                  {'passwordform' : passwordform, 
                   'profileform' : profileform,
                   'emailform' : emailform,
                   'invite_form': inviteform,
                   'success' : success,
                   'success_message' : success_message})