Exemple #1
0
def change_email_request():
    """Respond to existing user's request to change their email."""
    form = ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email = form.email.data
            token = current_user.generate_email_change_token(new_email)
            change_email_link = url_for('account.change_email', token=token,
                                        _external=True)
            get_queue().enqueue(
                send_email,
                recipient=new_email,
                subject='Confirm Your New Email',
                template='account/email/change_email',
                # current_user is a LocalProxy, we want the underlying user
                # object
                user=current_user._get_current_object(),
                change_email_link=change_email_link
            )
            flash('A confirmation link has been sent to {}.'.format(new_email),
                  'warning')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid email or password.', 'form-error')
    return render_template('account/manage.html', form=form)
def change_email_request():
    """Respond to existing user's request to change their email."""
    form = ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email = form.email.data
            token = current_user.generate_email_change_token(new_email)
            change_email_link = url_for_external('account.change_email',
                                                 token=token)
            get_queue().enqueue(
                send_email,
                recipient=new_email,
                subject='Confirm Your New Email',
                template='account/email/change_email',
                # current_user is a LocalProxy, we want the underlying user
                # object
                user=current_user._get_current_object(),
                change_email_link=change_email_link
            )
            flash('A confirmation link has been sent to {}.'.format(new_email),
                  'warning')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid email or password.', 'form-error')
    return render_template('account/manage.html', form=form)
def edit_profile():
    form = EditProfileForm()
    c = Config()
    if form.validate_on_submit():
        current_user.bio = form.bio.data
        current_user.address = form.address.data
        current_user.phone_number = form.phone_number.data
        current_user.website = form.website.data
        current_user.public_email = form.email.data
        current_user.f1 = form.featured1.data
        if form.image.data:
            filename = form.image.data.filename
            get_queue().enqueue(process_image, 
                                type='image',
                                filename=filename,
                                data =form.image.data.read(),
                                user_id=current_user.id)
        if form.pdf.data:
            filename = form.pdf.data.filename
            get_queue().enqueue(process_image, 
                                type='pdf',
                                filename=filename,
                                data =form.pdf.data.read(),
                                user_id=current_user.id)
        db.session.commit()
        return redirect(url_for('vendor.view_profile'))
    form.bio.data = current_user.bio
    form.address.data = current_user.address
    form.phone_number.data = current_user.phone_number
    form.website.data = current_user.website
    form.email.data = current_user.public_email
    form.featured1.data = current_user.f1
    return render_template('vendor/edit_profile.html', form=form)
def invite_user():
    """Invites a new user to create an account and set their own password."""
    form = InviteUserForm()
    if form.validate_on_submit():
        user = User(role=form.role.data,
                    first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    phone_number=parse_phone_number(form.phone_number.data))
        if user.is_worker():
            user.agencies = form.agency_affiliations.data

        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        invite_link = url_for_external('account.join_from_invite',
                                       user_id=user.id, token=token)
        get_queue().enqueue(
            send_email,
            recipient=user.email,
            subject='You Are Invited To Join',
            template='account/email/invite',
            user=user,
            invite_link=invite_link,
        )
        flash('User {} successfully invited'.format(user.full_name()),
              'form-success')
        return redirect(url_for('admin.invite_user'))
    return render_template('admin/invite_user.html', form=form)
Exemple #5
0
def index():
    editable_html_obj = EditableHTML.get_editable_html('contact')
    setattr(ContactForm,
            'category',
            SelectField('Category', choices=[(c.name, c.name) for c in ContactCategory.query.all()]))
    form = ContactForm()
    app = create_app(os.getenv('FLASK_CONFIG') or 'default')
    contact_email = app.config['ADMIN_EMAIL']
    if form.validate_on_submit():
        get_queue().enqueue(
            send_email,
            recipient=contact_email,
            subject=form.category.data,
            template='contact/email/contact',
            name=form.name.data,
            email=form.email.data,
            message=form.message.data
        )
        return redirect(url_for('main.index'))
    category_form = ContactCategoryForm()
    if category_form.validate_on_submit():
        if ContactCategory.query.filter_by(name = category_form.name.data).first() is not None:
            flash('Category \"{}\" already exists.'.format(category_form.name.data), 'form-error')
        else:
            new_category = ContactCategory(name=category_form.name.data)
            db.session.add(new_category)
            db.session.commit()
    categories = ContactCategory.query.all()
    return render_template('contact/index.html',
                            editable_html_obj=editable_html_obj,
                            form=form,
                            category_form=category_form,
                            categories=categories)
Exemple #6
0
def invite_user():
    """Invites a new user to create an account and set their own password."""
    form = InviteUserForm()
    if form.validate_on_submit():
        user = User(role=form.role.data,
                    first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        invite_link = url_for('account.join_from_invite',
                              user_id=user.id,
                              token=token,
                              _external=True)
        get_queue().enqueue(
            send_email,
            recipient=user.email,
            subject='You Are Invited To Join',
            template='account/email/invite',
            user=user,
            invite_link=invite_link,
        )
        flash('User {} successfully invited'.format(user.full_name()),
              'form-success')
    return render_template('admin/new_user.html', form=form)
Exemple #7
0
def analytics():
    try:
        wj = WorkerJob.query.first()
        if isinstance(wj, WorkerJob):
            S_job = get_queue('emolytics').fetch_job(wj.stream_job)
            C_job = get_queue('emolytics').fetch_job(wj.classify_job)
            if S_job:
                S_job.cancel()
            if C_job:
                C_job.cancel()
            WorkerJob.query.filter(WorkerJob.stream_job==wj.stream_job).delete(synchronize_session='fetch')
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
            except Exception, e:
                pass
        track = request.get_json(force=True)
        track = map(unicode.strip, track["text"].split(","))
        S_job = start_streaming.delay(track=track)
        C_job = classify.delay()
        wj = WorkerJob(S_job.id, C_job.id)
        db.session.add(wj)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
def reset_password_request():
    """Respond to existing user's request to reset their password."""
    if not current_user.is_anonymous():
        return redirect(url_for('main.index'))
    form = RequestResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_password_reset_token()
            reset_link = url_for_external('account.reset_password',
                                          token=token)
            get_queue().enqueue(
                send_email,
                recipient=user.email,
                subject='Reset Your Password',
                template='account/email/reset_password',
                user=user,
                reset_link=reset_link,
                next=request.args.get('next')
            )
        flash('A password reset link has been sent to {}.'
              .format(form.email.data),
              'warning')
        return redirect(url_for('account.login'))
    return render_template('account/reset_password.html', form=form)
def register():
    """Register a new user, and send them a confirmation email."""
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    phone_number=parse_phone_number(form.phone_number.data),
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        confirm_link = url_for_external('account.confirm', token=token)
        get_queue().enqueue(
            send_email,
            recipient=user.email,
            subject='Confirm Your Account',
            template='account/email/confirm',
            user=user,
            confirm_link=confirm_link
        )
        flash('A confirmation link has been sent to {}.'.format(user.email),
              'warning')
        return redirect(url_for('main.index'))
    return render_template('account/register.html', form=form)
Exemple #10
0
def edit_profile():
    form = EditProfileForm()
    c = Config()
    if form.validate_on_submit():
        current_user.bio = form.bio.data
        current_user.address = form.address.data
        current_user.phone_number = form.phone_number.data
        current_user.website = form.website.data
        current_user.public_email = form.email.data
        current_user.f1 = form.featured1.data
        if form.image.data:
            filename = form.image.data.filename
            get_queue().enqueue(process_image, 
                                type='image',
                                filename=filename,
                                data =form.image.data.read(),
                                user_id=current_user.id)
        if form.pdf.data:
            filename = form.pdf.data.filename
            get_queue().enqueue(process_image, 
                                type='pdf',
                                filename=filename,
                                data =form.pdf.data.read(),
                                user_id=current_user.id)
        db.session.commit()
        return redirect(url_for('vendor.view_profile'))
    form.bio.data = current_user.bio
    form.address.data = current_user.address
    form.phone_number.data = current_user.phone_number
    form.website.data = current_user.website
    form.email.data = current_user.public_email
    form.featured1.data = current_user.f1
    return render_template('vendor/edit_profile.html', form=form)
Exemple #11
0
def reset_password_request():
    """Respond to existing user's request to reset their password."""
    if not current_user.is_anonymous():
        return redirect(url_for('main.index'))
    form = RequestResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_password_reset_token()
            reset_link = url_for('account.reset_password', token=token,
                                 _external=True)
            get_queue().enqueue(
                send_email,
                recipient=user.email,
                subject='Reset Your Password',
                template='account/email/reset_password',
                user=user,
                reset_link=reset_link,
                next=request.args.get('next')
            )
        flash('A password reset link has been sent to {}.'
              .format(form.email.data),
              'warning')
        return redirect(url_for('account.login'))
    return render_template('account/reset_password.html', form=form)
Exemple #12
0
def delete_report(report_id):
    """Delete a report"""

    report = IncidentReport.query.filter_by(id=report_id).first()

    if report.picture_deletehash:
        # Asynchronously delete the report's image
        get_queue().enqueue(
            delete_image,
            deletehash=report.picture_deletehash,
            imgur_client_id=current_app.config['IMGUR_CLIENT_ID'],
            imgur_client_secret=current_app.config['IMGUR_CLIENT_SECRET'],
        )
    report_user_id = report.user_id

    db.session.delete(report)
    db.session.commit()
    flash('Successfully deleted report.', 'success')

    # TODO - address edge case where an admin clicks on their own report from
    # reports/all endpoint, should redirect back to /all. use cookies
    if report_user_id == current_user.id:
        return redirect(url_for('reports.view_my_reports'))
    else:
        return redirect(url_for('reports.view_reports'))
Exemple #13
0
def suggest(resource_id):
    """Create a suggestion for a resource."""
    basic_form = SuggestionBasicForm()
    if resource_id is None:
        name = None
        resource = None
    else:
        resource = Resource.query.get(resource_id)
        if resource is None:
            abort(404)
        name = resource.name
        basic_form.name.data = resource.name
        basic_form.address.data = resource.address
    advanced_form = SuggestionAdvancedForm()
    descriptors = Descriptor.query.all()
    for descriptor in descriptors:
        if descriptor.values:  # Fields for option descriptors.
            choices = [(str(i), v) for i, v in enumerate(descriptor.values)]
            setattr(SuggestionAdvancedForm,
                    descriptor.name,
                    SelectField(choices=choices))
        else:  # Fields for text descriptors
            setattr(SuggestionAdvancedForm, descriptor.name, TextAreaField())
    if basic_form.validate_on_submit():
        suggestion = Suggestion(
            resource_id=resource_id,
            suggestion_text=basic_form.suggestion_text.data,
            contact_name=basic_form.contact_name.data,
            contact_email=basic_form.contact_email.data,
            contact_phone_number=basic_form.contact_phone_number.data,
            resource_name=basic_form.name.data,
            resource_address=basic_form.address.data,
            submission_time=datetime.now(pytz.timezone('US/Eastern'))
        )
        db.session.add(suggestion)
        try:
            db.session.commit()
            app = create_app(os.getenv('FLASK_CONFIG') or 'default')
            contact_email = app.config['ADMIN_EMAIL']
            get_queue().enqueue(
                send_email,
                recipient=contact_email,
                subject='New Suggestion',
                template='suggestion/email/suggestion',
                name=basic_form.contact_name.data,
                email=basic_form.contact_email.data,
                phone=basic_form.contact_phone_number.data,
                message=basic_form.suggestion_text.data,
                resource_name=basic_form.name.data,
                resource_address=basic_form.address.data,
            )
            flash('Thanks for the suggestion!', 'success')
            return redirect(url_for('main.index'))
        except IntegrityError:
            db.session.rollback()
            flash('Database error occurred. Please try again.', 'error')
    return render_template('suggestion/suggest.html', name=name, basic_form=basic_form,
                            advanced_form=advanced_form)
def delete_user(user_id):
    """Delete a user's account."""
    if current_user.id == user_id:
        flash('You cannot delete your own account. Please ask another '
              'administrator to do this.', 'error')
    else:
        get_queue().enqueue(del_user, user_id=user_id)
        flash('Adding user to be processed for deletion', 'success')
    return redirect(url_for('admin.registered_users'))
Exemple #15
0
def delete_user(user_id):
    """Delete a user's account."""
    if current_user.id == user_id:
        flash(
            'You cannot delete your own account. Please ask another '
            'administrator to do this.', 'error')
    else:
        get_queue().enqueue(del_user, user_id=user_id)
        flash('Adding user to be processed for deletion', 'success')
    return redirect(url_for('admin.registered_users'))
Exemple #16
0
def run(id):
    job = Job.query.get_or_404(id)
    if current_user != job.author and not current_user.can(Permission.ADMINISTER):
        abort(404) # not 403 because we don't want to tell user that job exists
    form = JobRunForm()
    if form.validate_on_submit():
        get_queue("jobs").enqueue(run_job, job.id, form.date_range.data, form.start_date.data, form.end_date.data)
        flash('The job has been scheduled to run.')
        return redirect(url_for('.index', id=job.id))
    return render_template('job_run.html', form=form, job=job)
Exemple #17
0
def confirm_request():
    """Respond to new user's request to confirm their account."""
    token = current_user.generate_confirmation_token()
    confirm_link = url_for('account.confirm', token=token, _external=True)
    get_queue().enqueue(
        send_email,
        recipient=current_user.email,
        subject='Confirm Your Account',
        template='account/email/confirm',
        # current_user is a LocalProxy, we want the underlying user object
        user=current_user._get_current_object(),
        confirm_link=confirm_link)
    flash('A new confirmation link has been sent to {}.'.format(
        current_user.email), 'warning')
    return redirect(url_for('main.index'))
Exemple #18
0
def confirm_request():
    """Respond to new user's request to confirm their account."""
    token = current_user.generate_confirmation_token()
    confirm_link = url_for("account.confirm", token=token, _external=True)
    get_queue().enqueue(
        send_email,
        recipient=current_user.email,
        subject="Confirm Your Account",
        template="account/email/confirm",
        # current_user is a LocalProxy, we want the underlying user object
        user=current_user._get_current_object(),
        confirm_link=confirm_link,
    )
    flash("A new confirmation link has been sent to {}.".format(current_user.email), "warning")
    return redirect(url_for("main.index"))
Exemple #19
0
def join_from_invite(user_id, token):
    """
    Confirm new user's account with provided token and prompt them to set
    a password.
    """
    if current_user is not None and current_user.is_authenticated():
        flash("You are already logged in.", "error")
        return redirect(url_for("main.index"))

    new_user = User.query.get(user_id)
    if new_user is None:
        return redirect(404)

    if new_user.password_hash is not None:
        flash("You have already joined.", "error")
        return redirect(url_for("main.index"))

    if new_user.confirm_account(token):
        form = CreatePasswordForm()
        if form.validate_on_submit():
            new_user.password = form.password.data
            db.session.add(new_user)
            db.session.commit()
            flash(
                "Your password has been set. After you log in, you can "
                'go to the "Your Account" page to review your account '
                "information and settings.",
                "success",
            )
            return redirect(url_for("account.login"))
        return render_template("account/join_invite.html", form=form)
    else:
        flash(
            "The confirmation link is invalid or has expired. Another "
            "invite email with a new link has been sent to you.",
            "error",
        )
        token = new_user.generate_confirmation_token()
        invite_link = url_for("account.join_from_invite", user_id=user_id, token=token, _external=True)
        get_queue().enqueue(
            send_email,
            recipient=new_user.email,
            subject="You Are Invited To Join",
            template="account/email/invite",
            user=new_user,
            invite_link=invite_link,
        )
    return redirect(url_for("main.index"))
    def __init__(self, send_email_upon_creation=True, **kwargs):
        super(IncidentReport, self).__init__(**kwargs)
        if self.agency is not None and 'show_agency_publicly' not in kwargs:
            self.show_agency_publicly = self.agency.is_public

        if self.date is None:
            self.date = datetime.now(pytz.timezone(
                current_app.config['TIMEZONE']))
            self.date = self.date.replace(tzinfo=None)

        now = datetime.now(pytz.timezone(
                current_app.config['TIMEZONE'])).replace(tzinfo=None)
        if self.weather is None and self.location is not None and \
                (now - self.date < timedelta(minutes=1)):
            self.weather = get_current_weather(self.location)

        self.description = self.description.replace('\n', ' ').strip()
        self.description = self.description.replace('\r', ' ').strip()

        if send_email_upon_creation:
            all_reports_for_agency_link = url_for_external(
                'reports.view_reports')
            subject = '{} Idling Incident'.format(self.agency.name)

            if self.location.original_user_text is not None:
                subject += ' at {}'.format(self.location.original_user_text)

            for agency_worker in self.agency.users:
                get_queue().enqueue(
                    send_email,
                    recipient=agency_worker.email,
                    subject=subject,
                    template='reports/email/alert_workers',
                    incident_report=self,
                    user=agency_worker.full_name(),
                    all_reports_for_agency_link=all_reports_for_agency_link
                )

            if current_app.config['SEND_ALL_REPORTS_TO']:
                get_queue().enqueue(
                    send_email,
                    recipient=current_app.config['SEND_ALL_REPORTS_TO'],
                    subject=subject,
                    template='reports/email/alert_workers',
                    incident_report=self,
                    user=current_app.config['SEND_ALL_REPORTS_TO'],
                    all_reports_for_agency_link=all_reports_for_agency_link
                )
Exemple #21
0
def confirm_request():
    """Respond to new user's request to confirm their account."""
    token = current_user.generate_confirmation_token()
    confirm_link = url_for_external('account.confirm', token=token)
    get_queue().enqueue(
        send_email,
        recipient=current_user.email,
        subject='Confirm Your Account',
        template='account/email/confirm',
        # current_user is a LocalProxy, we want the underlying user object
        user=current_user._get_current_object(),
        confirm_link=confirm_link
    )
    flash('A new confirmation link has been sent to {}.'.
          format(current_user.email),
          'warning')
    return redirect(url_for('main.index'))
Exemple #22
0
def join_from_invite(user_id, token):
    """
    Confirm new user's account with provided token and prompt them to set
    a password.
    """
    if current_user is not None and current_user.is_authenticated():
        flash('You are already logged in.', 'error')
        return redirect(url_for('main.index'))

    new_user = User.query.get(user_id)
    if new_user is None:
        return redirect(404)

    if new_user.password_hash is not None:
        flash('You have already joined.', 'error')
        return redirect(url_for('main.index'))

    if new_user.confirm_account(token):
        form = CreatePasswordForm()
        if form.validate_on_submit():
            new_user.password = form.password.data
            db.session.add(new_user)
            db.session.commit()
            flash(
                'Your password has been set. After you log in, you can '
                'go to the "Your Account" page to review your account '
                'information and settings.', 'success')
            return redirect(url_for('account.login'))
        return render_template('account/join_invite.html', form=form)
    else:
        flash(
            'The confirmation link is invalid or has expired. Another '
            'invite email with a new link has been sent to you.', 'error')
        token = new_user.generate_confirmation_token()
        invite_link = url_for('account.join_from_invite',
                              user_id=user_id,
                              token=token,
                              _external=True)
        get_queue().enqueue(send_email,
                            recipient=new_user.email,
                            subject='You Are Invited To Join',
                            template='account/email/invite',
                            user=new_user,
                            invite_link=invite_link)
    return redirect(url_for('main.index'))
Exemple #23
0
    def post(self):
        data = request.json

        job = get_queue().enqueue(download_feed, feed=BOX_SERVICE.FEED_PATH)

        return {
            'job': {
                'id': job.id,
                'status': job.get_status(),
                'is_started': job.is_started,
            }
        }, 202
Exemple #24
0
def reset_password_request():
    """Respond to existing user's request to reset their password."""
    if not current_user.is_anonymous():
        return redirect(url_for("main.index"))
    form = RequestResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_password_reset_token()
            reset_link = url_for("account.reset_password", token=token, _external=True)
            get_queue().enqueue(
                send_email,
                recipient=user.email,
                subject="Reset Your Password",
                template="account/email/reset_password",
                user=user,
                reset_link=reset_link,
                next=request.args.get("next"),
            )
        flash("A password reset link has been sent to {}.".format(form.email.data), "warning")
        return redirect(url_for("account.login"))
    return render_template("account/reset_password.html", form=form)
Exemple #25
0
def sync():
    if not is_job_performable():
        abort(403)

    form = LoginForm()
    if form.validate_login():
        cardno, password = form.cardno.data, form.password.data
        job = get_queue('user').enqueue(generate_report, cardno, password)
        current_app.mongo.db.users.update({'cardno': g.user['cardno']}, {
            '$set': {'sync_job': job.id}
        })
        return redirect(url_for('.sync_progress'))
    return render_template('user/sync.html', form=form)
Exemple #26
0
def register():
    """Register a new user, and send them a confirmation email."""
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        confirm_link = url_for('account.confirm', token=token, _external=True)
        get_queue().enqueue(send_email,
                            recipient=user.email,
                            subject='Confirm Your Account',
                            template='account/email/confirm',
                            user=user,
                            confirm_link=confirm_link)
        flash('A confirmation link has been sent to {}.'.format(user.email),
              'warning')
        return redirect(url_for('main.index'))
    return render_template('account/register.html', form=form)
Exemple #27
0
    def post(self):
        # Will create a new build, receive the branch
        # args = parser.parse_args()
        parser = reqparse.RequestParser()
        parser.add_argument('branch', type=str)

        print parser.parse_args()

        branch = False
        if request.json:
            if 'branch' in request.json:
                branch = request.json['branch']
        else:
            return (
                {'error': 'The branch parameter is not present in the request'},
                requests.codes.bad_request,
            )

        identifier = uuid.uuid4().hex

        values = {
            'identifier': identifier,
            'branch': branch,
        }

        plugin_name = 'email'
        document = {
            'from': 'Stephane Wirtel <*****@*****.**>',
        }
        to_plugin = functools.partial(
            get_queue('builds').enqueue,
            'evy_worker.extension.invoke_plugin'
        )

        to_plugin(plugin_name, document)

        #get_queue('builds').enqueue('evy_worker.extension.plugin',
        #        'email', {'from': 'Stephane Wirtel <*****@*****.**>',
        #            })

        #get_queue('builds').enqueue('evy_worker.build.create',
        #                            branch,
        #                            identifier)

        headers = {
            'Location': url_for(BuildResource.__name__.lower(),
                                _method='GET', identifier=identifier),
            'X-Evy-Build': identifier,
        }

        return ({}, requests.codes.accepted, headers)
Exemple #28
0
def order():
    if(request.form.get("amountOz")):
        order=[]
        orderTuples = zip(request.form.getlist("amountOz"), request.form.getlist("name"))       
        for amount, name in orderTuples:
            #flash(amount + "  " + name)
            order.append(amount + "  " + name + "\n")
        #get_worker().work(True)
        q = get_queue().enqueue(pourDrink, orderTuples)
        return "Order: " + "".join(order)
        
		
    else:
        flash("No amount specified.")
    return redirect(url_for('drinkBot'))
def handle_picture_step(step, message_sid, twilio_hosted_media_url):
    """Handle a message from the user containing the report's picture."""
    image_job_id = None
    if twilio_hosted_media_url is not None:
        account_sid = current_app.config['TWILIO_ACCOUNT_SID']
        auth_token = current_app.config['TWILIO_AUTH_TOKEN']

        image_job_id = get_queue().enqueue(
            upload_image,
            imgur_client_id=current_app.config['IMGUR_CLIENT_ID'],
            imgur_client_secret=current_app.config['IMGUR_CLIENT_SECRET'],
            app_name=current_app.config['APP_NAME'],
            image_url=twilio_hosted_media_url
        ).id

        get_rq_scheduler().enqueue_in(
            timedelta(minutes=10),
            delete_mms,
            account_sid=account_sid,
            auth_token=auth_token,
            message_sid=message_sid
        )

    return step, image_job_id
Exemple #30
0
 def delay(*args, **kwargs):
     if app.config['TESTING']:
         return fn(*args, **kwargs)
     else:
         q = get_queue()
         return q.enqueue(fn, *args, **kwargs)
Exemple #31
0
 def delay(*args, **kwargs):
     if app.config['TESTING']:
         return fn(*args, **kwargs)
     else:
         q = get_queue()
         return q.enqueue(fn, *args, **kwargs)
Exemple #32
0
def empty():
    "Clear all jobs from queue"
    rq = get_queue()
    rq.empty()
Exemple #33
0
def empty():
    "Clear all jobs from queue"
    rq = get_queue()
    rq.empty()
def handle_message():
    """Called by Twilio when a text message is received."""
    body = str(request.values.get('Body')).lower().strip()
    num_media = int(request.values.get('NumMedia'))
    twilio_hosted_media_url = str(request.values.get('MediaUrl0')) \
        if num_media > 0 else None
    message_sid = str(request.values.get('MessageSid'))
    phone_number = str(request.values.get('From'))

    twiml = twilio.twiml.Response()

    # Retrieve incident cookies
    step = int(request.cookies.get('messagecount', 0))
    vehicle_id = str(request.cookies.get('vehicle_id', ''))
    agency_name = str(request.cookies.get('agency_name', ''))
    license_plate = str(request.cookies.get('license_plate', ''))
    duration = int(request.cookies.get('duration', 0))
    description = str(request.cookies.get('description', ''))
    location = str(request.cookies.get('location', ''))
    picture_url = str(request.cookies.get('picture_url', ''))

    if 'report' == body.lower():
        # reset report variables/cookies
        vehicle_id = ''
        agency_name = ''
        license_plate = ''
        duration = 0
        description = ''
        location = ''
        picture_url = ''

        step = handle_start_report(twiml)

    elif step == STEP_LOCATION:
        location, step = handle_location_step(body, step, twiml)

    elif step == STEP_AGENCY:
        agency_name, step = handle_agency_step(body, step, twiml)

    elif step == STEP_OTHER_AGENCY:
        agency_name, step = handle_other_agency_step(body, step, twiml)

    elif step == STEP_LICENSE_PLATE:
        license_plate, step = handle_license_plate_step(body, step, twiml)

    elif step == STEP_VEHICLE_ID:
        vehicle_id, step = handle_vehicle_id_step(body, step, twiml)

    elif step == STEP_DURATION:
        duration, step = handle_duration_step(body, step, twiml)

    elif step == STEP_DESCRIPTION:
        description, step = handle_description_step(body, step, twiml)

    elif step == STEP_PICTURE:
        step, image_job_id = handle_picture_step(step, message_sid,
                                                 twilio_hosted_media_url)

        new_incident = handle_create_report(agency_name, description, duration,
                                            license_plate, location,
                                            picture_url, vehicle_id,
                                            phone_number)

        twiml.message('Thanks! See your report on the map at {}'
                      .format(url_for_external('main.index')))

        if new_incident.user is None:
            twiml.message('Want to keep track of all your reports? Create an '
                          'account at {}'
                          .format(url_for_external('account.register')))
        else:
            twiml.message('See all your reports at {}'
                          .format(url_for_external('reports.view_my_reports')))

        if image_job_id is not None:
            get_queue().enqueue(
                attach_image_to_incident_report,
                depends_on=image_job_id,
                incident_report=new_incident,
                image_job_id=image_job_id,
            )

        # reset report variables/cookies
        step = STEP_INIT

    else:
        twiml.message('Welcome to {}! Please reply "report" to report an '
                      'idling incident.'
                      .format(current_app.config['APP_NAME']))

    response = make_response(str(twiml))

    set_cookie(response, 'messagecount', str(step))
    set_cookie(response, 'agency_name', agency_name)
    set_cookie(response, 'vehicle_id', vehicle_id)
    set_cookie(response, 'license_plate', license_plate)
    set_cookie(response, 'duration', str(duration))
    set_cookie(response, 'description', description)
    set_cookie(response, 'location', location)
    set_cookie(response, 'picture_url', picture_url)

    return response