Beispiel #1
0
def modsub_page():
    '''Dashboard Modify Subscription:
    This will allow a user to modify their subscription and account plan
    '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/mod-subscription'
        data['uid'] = user.uid
        tmpl = 'member/mod-subscription.html'
        data['js_bottom'].append('forms/subscribe.js')
        form = []
        from generalforms import subscribe

        payment = __import__("payments." + user.payments, globals(), locals(),
                             ['Payments'], -1)

        subscription = payment.Payments(user=user,
                                        config=app.config,
                                        rdb=g.rdb_conn)
        if request.method == "POST":
            if data['upgraded'] is True:
                result = subscription.adjust(request)
            else:
                result = subscription.create(request)

            if result is True:
                if data['upgraded'] is True:
                    flash('Adjustment to subscription successful', 'success')
                else:
                    data['upgraded'] = True
                    flash('Successfully Subscribed!', 'success')
                newdata = startData(user)
                data['limit'] = newdata['limit']
                data['rlimit'] = newdata['rlimit']
                data['acttype'] = newdata['acttype']
                data['subplans'] = newdata['subplans']
                data['cost'] = newdata['cost']
                data['subscription'] = newdata['subscription']
            else:
                flash('Unable to adjust subscription please notify support',
                      'danger')
        if data['upgraded'] is True:
            form = subscribe.AddPackForm(request.form)
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #2
0
def modsub_page():
    '''Dashboard Modify Subscription:
    This will allow a user to modify their subscription and account plan
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/mod-subscription'
        data['uid'] = user.uid
        tmpl = 'member/mod-subscription.html'
        data['js_bottom'].append('forms/subscribe.js')
        form = []
        from generalforms import subscribe

        payment = __import__("payments." + user.payments, globals(),
                             locals(), ['Payments'], -1)

        subscription = payment.Payments(user=user, config=app.config, rdb=g.rdb_conn)
        if request.method == "POST":
            if data['upgraded'] is True:
                result = subscription.adjust(request)
            else:
                result = subscription.create(request)

            if result is True:
                if data['upgraded'] is True:
                    flash('Adjustment to subscription successful', 'success')
                else:
                    data['upgraded'] = True
                    flash('Successfully Subscribed!', 'success')
                newdata = startData(user)
                data['limit'] = newdata['limit']
                data['rlimit'] = newdata['rlimit']
                data['acttype'] = newdata['acttype']
                data['subplans'] = newdata['subplans']
                data['cost'] = newdata['cost']
                data['subscription'] = newdata['subscription']
            else:
                flash('Unable to adjust subscription please notify support', 'danger')
        if data['upgraded'] is True:
            form = subscribe.AddPackForm(request.form)
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #3
0
def managereactions_page():
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/'
        data['js_bottom'] = [ 'member/reactions.js' ]
        tmpl = 'member/reactions.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass
        data['reactions'] = user.getReactions(g.rdb_conn)
        if len(data['reactions']) < 1:
            data['reacts'] = False
        else:
            data['reacts'] = True
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #4
0
def managereactions_page():
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/'
        data['js_bottom'] = [ 'member/reactions.js' ]
        tmpl = 'member/reactions.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass
        data['reactions'] = user.getReactions(g.rdb_conn)
        if len(data['reactions']) < 1:
            data['reacts'] = False
        else:
            data['reacts'] = True
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #5
0
def detailhistory_page(cid, hid):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/detail-history/' + hid
        tmpl = 'monitors/detail-history.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            monitor = Monitor()
            monitor.get(cid, g.rdb_conn)
            if monitor.uid == user.uid:
                data['monitor'] = {
                    'cid': monitor.cid,
                    'name': monitor.name,
                    'ctype': monitor.ctype,
                    'uid': monitor.uid,
                    'data': monitor.data
                }
                data['monitor-history'] = monitor.history(
                    method="detail-history", hid=hid, rdb=g.rdb_conn)
            else:
                flash('This monitor does not belong to your user.', 'warning')
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #6
0
def detailhistory_page(cid, hid):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/detail-history/' + hid
        tmpl = 'monitors/detail-history.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            monitor = Monitor()
            monitor.get(cid, g.rdb_conn)
            if monitor.uid == user.uid:
                data['monitor'] = {
                    'cid': monitor.cid,
                    'name': monitor.name,
                    'ctype': monitor.ctype,
                    'uid': monitor.uid,
                    'data': monitor.data
                }
                data['monitor-history'] = monitor.history(
                    method="detail-history", hid=hid, rdb=g.rdb_conn)
            else:
                flash('This monitor does not belong to your user.', 'warning')
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #7
0
def dashboard_page():
    ''' Dashboard: Generate the Welcome/Status page for the dashboard '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard'
        data['js_bottom'].append("member/screen-o-death.js")
        data['js_bottom'].append("member/screen-o-death-chart.js")
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            page = render_template('member/mod-subscription.html', data=data)
        else:

            data['monitors'] = user.getMonitors(g.rdb_conn)
            data['reactions'] = user.getReactions(g.rdb_conn)
            data['monevents'] = user.getEvents(g.rdb_conn)
            data['moneventsnum'] = len(data['monevents'])
            data['monstats'] = {'true': 0,
                                'unknown': 0,
                                'false': 0}
            for key in data['monitors'].keys():
                if "true" in data['monitors'][key]['status']:
                    data['monstats']['true'] = data[
                        'monstats']['true'] + 1
                elif "false" in data['monitors'][key]['status']:
                    data['monstats']['false'] = data['monstats']['false'] + 1
                else:
                    data['monstats']['unknown'] = data[
                        'monstats']['unknown'] + 1

            # If there are no monitors print a welcome message
            if len(data['monitors']) < 1 and len(data['reactions']) < 1:
                data['welcome'] = True
            else:
                data['welcome'] = False

            if len(data['monitors']) < 1:
                data['mons'] = False
            else:
                data['mons'] = True

            if len(data['reactions']) < 1:
                data['reacts'] = False
            else:
                data['reacts'] = True

            from generalforms import subscribe
            form = subscribe.AddPackForm(request.form)
            page = render_template(
                'member/screen-o-death.html', data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #8
0
def dashboard_page():
    ''' Dashboard: Generate the Welcome/Status page for the dashboard '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard'
        data['js_bottom'].append("member/screen-o-death.js")
        data['js_bottom'].append("member/screen-o-death-chart.js")
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            page = render_template('member/mod-subscription.html', data=data)
        else:

            data['monitors'] = user.getMonitors(g.rdb_conn)
            data['reactions'] = user.getReactions(g.rdb_conn)
            data['monevents'] = user.getEvents(g.rdb_conn)
            data['moneventsnum'] = len(data['monevents'])
            data['monstats'] = {'healthy': 0,
                                'unknown': 0,
                                'failed': 0}
            for key in data['monitors'].keys():
                if "healthy" in data['monitors'][key]['status']:
                    data['monstats']['healthy'] = data[
                        'monstats']['healthy'] + 1
                elif "failed" in data['monitors'][key]['status']:
                    data['monstats']['failed'] = data['monstats']['failed'] + 1
                else:
                    data['monstats']['unknown'] = data[
                        'monstats']['unknown'] + 1

            # If there are no monitors print a welcome message
            if len(data['monitors']) < 1 and len(data['reactions']) < 1:
                data['welcome'] = True
            else:
                data['welcome'] = False

            if len(data['monitors']) < 1:
                data['mons'] = False
            else:
                data['mons'] = True

            if len(data['reactions']) < 1:
                data['reacts'] = False
            else:
                data['reacts'] = True

            from generalforms import subscribe
            form = subscribe.AddPackForm(request.form)
            page = render_template(
                'member/screen-o-death.html', data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #9
0
def viewhistory_page(cid, start, limit):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/view-history/' + cid
        tmpl = 'monitors/view-history.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            monitor = Monitor()
            monitor.config = app.config
            monitor.get(cid, g.rdb_conn)
            if monitor.uid == user.uid:
                data['monitor'] = {
                    'cid': monitor.cid,
                    'name': monitor.name,
                    'ctype': monitor.ctype,
                    'uid': monitor.uid,
                    'data': monitor.data
                }
                chktime = time.time() - float(data['dataret'])
                data['monitor-history-count'] = monitor.history(method="count",
                                                                time=chktime,
                                                                rdb=g.rdb_conn)
                data['monitor-history'] = monitor.history(method="mon-history",
                                                          time=chktime,
                                                          start=int(start),
                                                          limit=int(limit),
                                                          rdb=g.rdb_conn)
                data['monitor-history-paging'] = []
                data['monitor-history-paging-start'] = int(start)
                cur = 0
                while cur < data['monitor-history-count'] - 200:
                    cur = cur + 200
                    data['monitor-history-paging'].append(cur)
            else:
                flash('This monitor does not belong to your user.', 'warning')
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #10
0
def userpref_page():
    '''
    Dashbaord User Preferences:
    This will allow a user to change user preferences, i.e. Password
    '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Start processing the change password form
            form = ChangePassForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    result = user.checkPass(form.old_password.data, g.rdb_conn)
                    if result:
                        update = user.setPass(form.password.data, g.rdb_conn)
                        if update:
                            print(
                                "/dashboard/user-preferences - Password changed"
                            )
                            flash('Password successfully changed.', 'success')
                        else:
                            print("/dashboard/user-preferences - \
                                  Password change failed")
                            flash('Password change was unsuccessful.',
                                  'danger')
                    else:
                        print(
                            "/login - User change password error: wrong old password"
                        )
                        flash('Old password does not seem valid.', 'danger')
            data['url'] = '/dashboard/user-preferences'
            tmpl = 'member/user-preferences.html'
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #11
0
def viewhistory_page(cid, start, limit):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/view-history/' + cid
        tmpl = 'monitors/view-history.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            monitor = Monitor()
            monitor.config = app.config
            monitor.get(cid, g.rdb_conn)
            if monitor.uid == user.uid:
                data['monitor'] = {
                    'cid': monitor.cid,
                    'name': monitor.name,
                    'ctype': monitor.ctype,
                    'uid': monitor.uid,
                    'data': monitor.data
                }
                chktime = time.time() - float(data['dataret'])
                data['monitor-history-count'] = monitor.history(
                    method="count", time=chktime, rdb=g.rdb_conn)
                data['monitor-history'] = monitor.history(
                    method="mon-history", time=chktime,
                    start=int(start), limit=int(limit), rdb=g.rdb_conn)
                data['monitor-history-paging'] = []
                data['monitor-history-paging-start'] = int(start)
                cur = 0
                while cur < data['monitor-history-count'] - 200:
                    cur = cur + 200
                    data['monitor-history-paging'].append(cur)
            else:
                flash('This monitor does not belong to your user.', 'warning')
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #12
0
def monitors_page():
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/monitors/'
        data['monitor_list'] = app.config['MONITORS']
        tmpl = 'monitors/index.html'
        data['js_bottom'] = [
            'monitors/monitorlist.js',
        ]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass

        data['monitors'] = user.getMonitors(g.rdb_conn)
        data['reactions'] = user.getReactions(g.rdb_conn)
        # If there are no monitors print a welcome message
        if len(data['monitors']) < 1 and len(data['reactions']) < 1:
            data['welcome'] = True
        else:
            data['welcome'] = False

        if len(data['monitors']) < 1:
            data['mons'] = False
        else:
            data['mons'] = True

        if len(data['reactions']) < 1:
            data['reacts'] = False
        else:
            data['reacts'] = True
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #13
0
def monitors_page():
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/monitors/'
        data['monitor_list'] = app.config['MONITORS']
        tmpl = 'monitors/index.html'
        data['js_bottom'] = ['monitors/monitorlist.js',]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass

        data['monitors'] = user.getMonitors(g.rdb_conn)
        data['reactions'] = user.getReactions(g.rdb_conn)
        # If there are no monitors print a welcome message
        if len(data['monitors']) < 1 and len(data['reactions']) < 1:
            data['welcome'] = True
        else:
            data['welcome'] = False

        if len(data['monitors']) < 1:
            data['mons'] = False
        else:
            data['mons'] = True

        if len(data['reactions']) < 1:
            data['reacts'] = False
        else:
            data['reacts'] = True
        page = render_template(tmpl, data=data)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #14
0
def reactions_page():
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/'
        tmpl = 'reactions/index.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass
        page = render_template(tmpl, data=data)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #15
0
def reactions_page():
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/'
        tmpl = 'reactions/index.html'
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            pass
        page = render_template(tmpl, data=data)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #16
0
def userpref_page():
    '''
    Dashbaord User Preferences:
    This will allow a user to change user preferences, i.e. Password
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Start processing the change password form
            form = ChangePassForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    result = user.checkPass(form.old_password.data, g.rdb_conn)
                    if result:
                        update = user.setPass(form.password.data, g.rdb_conn)
                        if update:
                            print("/dashboard/user-preferences - Password changed")
                            flash('Password successfully changed.', 'success')
                        else:
                            print("/dashboard/user-preferences - \
                                  Password change failed")
                            flash('Password change was unsuccessful.', 'danger')
                    else:
                        print("/login - User change password error: wrong old password")
                        flash('Old password does not seem valid.', 'danger')
            data['url'] = '/dashboard/user-preferences'
            tmpl = 'member/user-preferences.html'
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #17
0
def userpref_page():
    '''
    Dashbaord User Preferences:
    This will allow a user to change user preferences, i.e. Password
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            # Start processing the change password form
            form = ChangePassForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    result = user.setPass(form.password.data, g.rdb_conn)
                    if result:
                        data['msg'] = "Password successfully changed"
                        print("/dashboard/user-preferences - Password changed")
                        data['error'] = False
                    else:
                        data['msg'] = "Password change was unsuccessful"
                        print("/dashboard/user-preferences - Password change failed")
                        data['error'] = True
            data['url'] = '/dashboard/user-preferences'
            tmpl = 'member/user-preferences.html'
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #18
0
def editcheck_page(cname, cid):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-monitors/' + cname + "/" + cid
        tmpl = 'monitors/' + cname + '.html'
        data['edit'] = True
        data['js_bottom'] = ['monitors/base.js', 'monitors/' + cname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__("monitorforms." + cname, globals(), locals(),
                               ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            oldmonitor = Monitor()
            oldmonitor.get(cid, g.rdb_conn)
            if oldmonitor.uid == user.uid:
                data['monitor'] = {
                    'cid': oldmonitor.cid,
                    'name': oldmonitor.name,
                    'uid': oldmonitor.uid,
                    'ctype': oldmonitor.ctype,
                    'url': oldmonitor.url,
                    'data': oldmonitor.data
                }
            # Check if the form contains the timer SelectField
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            reactdefaults = []
            for key in data['reactions'].keys():
                reactchoices.append((data['reactions'][key]['id'],
                                     data['reactions'][key]['name']))
                if data['reactions'][key]['id'] in \
                        data['monitor']['data']['reactions']:
                    reactdefaults.append(data['reactions'][key]['id'])
            form.reactions.choices = reactchoices
            for item in form.__iter__():
                if item.type == "SelectField" or\
                        item.type == "SelectMultipleField":
                    item.default = data['monitor']['data'][item.name]

            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.cid = cid
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = oldmonitor.url
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    monitor.data = tmpdata
                    data['monitor'] = {
                        'cid': monitor.cid,
                        'name': monitor.name,
                        'uid': monitor.uid,
                        'ctype': monitor.ctype,
                        'url': monitor.url,
                        'data': monitor.data
                    }
                    reactdefaults = data['monitor']['data']['reactions']
                    # Check if the user already exceeds their limit
                    if oldmonitor.uid == user.uid:
                        # Create the monitor if all checks out
                        results = monitor.editMonitor(g.rdb_conn)
                    else:
                        results = "NotYours"
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: not users".format(cname))
                        flash("This Monitor doesn't appear to be yours.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: exists".format(cname))
                        flash(
                            'This monitor seems to already exist. \
                               Try using a different name.', 'danger')
                    elif results is False:
                        print("/dashboard/edit-monitors/{0} - Monitor \
                              edit failed: unknown reason".format(cname))
                        flash('Could not edit monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: too many".format(cname))
                        flash(
                            'You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added', 1)
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit successful").format(cname)
                        flash(
                            'Monitor "{0}" successfully edited'.format(
                                monitor.name), 'success')
                else:
                    print("/dashboard/edit-monitors/{0} - \
                          Monitor edit failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
            # Process form to display defaults
            if form.__contains__("timer"):
                form.timer.default = data['monitor']['data']['timer']
            form.reactions.default = reactdefaults
            form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #19
0
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.config = app.config
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #20
0
def modsub_page():
    '''Dashboard Modify Subscription:
    This will allow a user to modify their subscription and account plan
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/mod-subscription'
        data['uid'] = user.uid
        tmpl = 'member/mod-subscription.html'
        data['js_bottom'].append('forms/subscribe.js')
        form = []
        headers = {
            "content-type": "application/json",
            "Authorization": app.config['ASSEMBLY_PRIVATE_KEY']
        }
        from generalforms import subscribe
        if data['acttype'] == "Lite":
            # Upgrade Users
            if request.method == "POST" and \
                    "stripeToken" in request.form and "plan" in request.form:
                stripeToken = request.form['stripeToken']
                plan = request.form['plan']
                if stripeToken:
                    result = None
                    monitor = Monitor()
                    payload = {
                        'email': user.email,
                        'quantity': monitor.count(user.uid, g.rdb_conn),
                        'card': stripeToken,
                        'plan': plan
                    }
                    json_payload = json.dumps(payload)
                    url = app.config['ASSEMBLY_PAYMENTS_URL'] + "/customers"
                    print ("Making request to %s") % url
                    try:
                        # Send Request to Assembly to create user and subscribe
                        # them to desired plan
                        result = requests.post(
                            url=url, headers=headers,
                            data=json_payload, verify=True)
                    except:
                        print("Critical Error making request to ASM Payments")
                        data['msg'] = "There was an error processing your card details"
                        data['error'] = True
                    print(
                        "Got %d status code from Assembly") % result.status_code
                    if result.status_code >= 200 and result.status_code <= 299:
                        rdata = json.loads(result.text)
                        user.stripeid = rdata['id']
                        user.stripe = stripeToken
                        user.subplans = payload['quantity']
                        user.subscription = payload['plan']
                        user.acttype = "pro"
                        print("Setting UID %s Subscription to: %s") % (
                            user.uid, user.acttype)
                        subres = user.setSubscription(g.rdb_conn)
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' User Upgrades', 1)
                        if subres:
                            newdata = startData(user)
                            data['limit'] = newdata['limit']
                            data['rlimit'] = newdata['rlimit']
                            data['acttype'] = newdata['acttype']
                            data['subplans'] = newdata['subplans']
                            data['cost'] = newdata['cost']
                            data['subscription'] = newdata['subscription']
                            data['msg'] = "Subscription successfully created"
                            data['error'] = False
                        else:
                            data[
                                'msg'] = "Subscription not successfully created"
                            data['error'] = True
        # Increase subscription
        if data['acttype'] != "Lite":
            form = subscribe.AddPackForm(request.form)
            if request.method == "POST" and "stripeToken" not in request.form:
                if form.validate():
                    add_packs = int(form.add_packs.data)
                    # Set subscription quantity to desired monitor count
                    payload = {'quantity': add_packs}
                    json_payload = json.dumps(payload)
                    url = app.config[
                        'ASSEMBLY_PAYMENTS_URL'] + "/customers/" + user.stripeid
                    print("Making request to %s") % url
                    try:
                        # Get Subscription ID
                        result = requests.get(
                            url=url, headers=headers, verify=True)
                        if result.status_code == 200:
                            rdata = json.loads(result.text)
                            subsid = rdata['subscriptions']['data'][0]['id']
                            url = url + "/subscriptions/" + subsid
                            print("Making request to %s") % url
                            # Set Quantity
                            try:
                                result = requests.put(
                                    url=url, headers=headers,
                                    data=json_payload, verify=True)
                            except:
                                data['msg'] = "An error occured while processing the form"
                                data['error'] = True
                                print("Critical Error making request to ASM Payments")
                        else:
                            data['msg'] = "An error occured while processing the form"
                            data['error'] = True
                    except:
                        data['msg'] = "An error occured while processing the form"
                        data['error'] = True
                        print("Critical Error making request to ASM Payments")
                    print(
                        "Got %d status code from Assembly") % result.status_code
                    if result.status_code >= 200 and result.status_code <= 299:
                        user.subplans = add_packs
                        # Save user config
                        print("Setting subscription count to %d for user %s") % (add_packs, user.uid)
                        subres = user.setSubscription(g.rdb_conn)
                        if subres:
                            newdata = startData(user)
                            data['limit'] = newdata['limit']
                            data['rlimit'] = newdata['rlimit']
                            data['acttype'] = newdata['acttype']
                            data['subplans'] = newdata['subplans']
                            data['cost'] = newdata['cost']
                            data['msg'] = "Subscription successfully modified"
                            data['error'] = False
                        else:
                            data['msg'] = "Unknown error modifing subscription"
                            data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #21
0
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js', ]
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            reaction.config = app.config
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/create.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.config = app.config
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        print("/dashboard/reactions/{0} - \
                            Reaction edit failed: not owner".format(rname))
                        flash("It doesn't appear that you own this reaction.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction seems to already exist. \
                              Try using a different name.', 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction can not be edited \
                              as it does not exist.', 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited.', 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction edit success".format(rname))
                        flash('Reaction "{0}" successfully \
                              added.'.format(reaction2.name), 'danger')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction edit failed: form invalid".format(rname))
                    flash('Form is not valid.', 'danger')
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #22
0
def modsub_page():
    '''Dashboard Modify Subscription:
    This will allow a user to modify their subscription and account plan
    '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/mod-subscription'
        data['uid'] = user.uid
        tmpl = 'member/mod-subscription.html'
        data['js_bottom'].append('forms/subscribe.js')
        form = []
        headers = {
            "content-type": "application/json",
            "Authorization": app.config['ASSEMBLY_PRIVATE_KEY']
        }
        from generalforms import subscribe
        if data['acttype'] == "Lite":
            # Upgrade Users
            if request.method == "POST" and \
                    "stripeToken" in request.form and "plan" in request.form:
                stripeToken = request.form['stripeToken']
                plan = request.form['plan']
                if stripeToken:
                    result = None
                    monitor = Monitor()
                    payload = {
                        'email': user.email,
                        'quantity': monitor.count(user.uid, g.rdb_conn),
                        'card': stripeToken,
                        'plan': plan
                    }
                    json_payload = json.dumps(payload)
                    url = app.config['ASSEMBLY_PAYMENTS_URL'] + "/customers"
                    print("Making request to %s") % url
                    try:
                        # Send Request to Assembly to create user and subscribe
                        # them to desired plan
                        result = requests.post(url=url,
                                               headers=headers,
                                               data=json_payload,
                                               verify=True)
                    except:
                        print("Critical Error making request to ASM Payments")
                        flash(
                            'There was an error processing \
                              your card details.', 'danger')
                    print("Got {0} status code from Assembly".format(
                        result.status_code))
                    if result.status_code >= 200 and result.status_code <= 299:
                        rdata = json.loads(result.text)
                        user.stripeid = rdata['id']
                        user.stripe = stripeToken
                        user.subplans = payload['quantity']
                        user.subscription = payload['plan']
                        user.acttype = "pro"
                        print("Setting UID %s Subscription to: %s") % (
                            user.uid, user.acttype)
                        subres = user.setSubscription(g.rdb_conn)
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' User Upgrades', 1)
                        if subres:
                            newdata = startData(user)
                            data['limit'] = newdata['limit']
                            data['rlimit'] = newdata['rlimit']
                            data['acttype'] = newdata['acttype']
                            data['subplans'] = newdata['subplans']
                            data['cost'] = newdata['cost']
                            data['subscription'] = newdata['subscription']
                            flash('Subscription successfully created.',
                                  'success')
                        else:
                            flash('Subscription not successfully created.',
                                  'danger')
        # Increase subscription
        if data['acttype'] != "Lite":
            form = subscribe.AddPackForm(request.form)
            if request.method == "POST" and "stripeToken" not in request.form:
                if form.validate():
                    add_packs = int(form.add_packs.data)
                    # Set subscription quantity to desired monitor count
                    payload = {'quantity': add_packs}
                    json_payload = json.dumps(payload)
                    url = app.config[
                        'ASSEMBLY_PAYMENTS_URL'] + "/customers/" + user.stripeid
                    print("Making request to %s") % url
                    try:
                        # Get Subscription ID
                        result = requests.get(url=url,
                                              headers=headers,
                                              verify=True)
                        if result.status_code == 200:
                            rdata = json.loads(result.text)
                            subsid = rdata['subscriptions']['data'][0]['id']
                            url = url + "/subscriptions/" + subsid
                            print("Making request to %s") % url
                            # Set Quantity
                            try:
                                result = requests.put(url=url,
                                                      headers=headers,
                                                      data=json_payload,
                                                      verify=True)
                            except:
                                print("Critical Error making \
                                      request to ASM Payments")
                                flash(
                                    'An error occured while \
                                      processing the form.', 'danger')
                        else:
                            flash(
                                'An error occured while \
                                  processing the form.', 'danger')
                    except:
                        print("Critical Error making request to ASM Payments")
                        flash(
                            'An error occured \
                              while processing the form.', 'danger')
                    print("Got {0} status code from Assembly".format(
                        result.status_code))
                    if result.status_code >= 200 and result.status_code <= 299:
                        user.subplans = add_packs
                        # Save user config
                        print("Setting subscription count to \
                              {0} for user {1}".format(add_packs, user.uid))
                        subres = user.setSubscription(g.rdb_conn)
                        if subres:
                            newdata = startData(user)
                            data['limit'] = newdata['limit']
                            data['rlimit'] = newdata['rlimit']
                            data['acttype'] = newdata['acttype']
                            data['subplans'] = newdata['subplans']
                            data['cost'] = newdata['cost']
                            flash('Subscription successfully modified.',
                                  'success')
                        else:
                            flash('Unknown error modifing subscription.',
                                  'danger')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #23
0
def addreaction_page(rname):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__("reactionforms." + rname, globals(), locals(),
                                ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        data[
                            'msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data[
                            'msg'] = "This reaction can not be edited as it does not exist: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: doesnt exist"
                        ) % rname
                        data['error'] = True
                    elif results == "edit true":
                        data[
                            'msg'] = "Reaction successfully edited: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit successful"
                        ) % rname
                        data['error'] = False
                    elif results == "edit false":
                        data[
                            'msg'] = "Reaction not successfully edited: %s" % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    elif results == "toomany":
                        data[
                            'msg'] = "Could not create reaction: Too many reactions already created [%d]" % data[
                                'rlimit']
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: too many"
                        ) % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction creation failed: unknown"
                        ) % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data[
                            'msg'] = 'Reaction "%s" successfully added' % reaction.name
                        print(
                            "/dashboard/reactions/%s - Reaction creation successful"
                        ) % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print(
                        "/dashboard/reactions/%s - Reaction creation failed: form invalid"
                    ) % rname
                    data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #24
0
def editcheck_page(cname, cid):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-monitors/' + cname + "/" + cid
        tmpl = 'monitors/' + cname + '.html'
        data['edit'] = True
        data['js_bottom'] = ['monitors/base.js', 'monitors/' + cname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__(
                "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            oldmonitor = Monitor()
            oldmonitor.get(cid, g.rdb_conn)
            if oldmonitor.uid == user.uid:
                data['monitor'] = {
                    'cid': oldmonitor.cid,
                    'name': oldmonitor.name,
                    'uid': oldmonitor.uid,
                    'ctype': oldmonitor.ctype,
                    'url': oldmonitor.url,
                    'data': oldmonitor.data
                }
            # Check if the form contains the timer SelectField
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            reactdefaults = []
            for key in data['reactions'].keys():
                reactchoices.append(
                    (data['reactions'][key]['id'],
                        data['reactions'][key]['name']))
                if data['reactions'][key]['id'] in \
                        data['monitor']['data']['reactions']:
                    reactdefaults.append(data['reactions'][key]['id'])
            form.reactions.choices = reactchoices
            for item in form.__iter__():
                if item.type == "SelectField" or\
                        item.type == "SelectMultipleField":
                    item.default = data['monitor']['data'][item.name]

            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.cid = cid
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = oldmonitor.url
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    monitor.data = tmpdata
                    data['monitor'] = {
                        'cid': monitor.cid,
                        'name': monitor.name,
                        'uid': monitor.uid,
                        'ctype': monitor.ctype,
                        'url': monitor.url,
                        'data': monitor.data
                    }
                    reactdefaults = data['monitor']['data']['reactions']
                    # Check if the user already exceeds their limit
                    if oldmonitor.uid == user.uid:
                        # Create the monitor if all checks out
                        results = monitor.editMonitor(g.rdb_conn)
                    else:
                        results = "NotYours"
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: not users".format(cname))
                        flash("This Monitor doesn't appear to be yours.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: exists".format(cname))
                        flash('This monitor seems to already exist. \
                               Try using a different name.', 'danger')
                    elif results is False:
                        print("/dashboard/edit-monitors/{0} - Monitor \
                              edit failed: unknown reason".format(cname))
                        flash('Could not edit monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: too many".format(cname))
                        flash('You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added',
                            1
                        )
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit successful").format(cname)
                        flash('Monitor "{0}" successfully edited'.format(
                            monitor.name), 'success')
                else:
                    print("/dashboard/edit-monitors/{0} - \
                          Monitor edit failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
            # Process form to display defaults
            if form.__contains__("timer"):
                form.timer.default = data['monitor']['data']['timer']
            form.reactions.default = reactdefaults
            form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #25
0
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/index.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__("reactionforms." + rname, globals(), locals(),
                                ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/' + rname + '.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        data[
                            'msg'] = "It doesn't appear that you own this reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: not owner"
                        ) % rname
                        data['error'] = True
                    if results == "exists":
                        data[
                            'msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data[
                            'msg'] = "This reaction can not be edited as it does not exist: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: exists"
                        ) % rname
                        data['error'] = True
                    elif results == "edit true":
                        data[
                            'msg'] = "Reaction successfully edited: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit successful"
                        ) % rname
                        data['error'] = False
                    elif results == "edit false":
                        data[
                            'msg'] = "Reaction not successfully edited: %s" % reaction2.name
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print(
                            "/dashboard/reactions/%s - Reaction edit failed: unknown"
                        ) % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data[
                            'msg'] = 'Reaction "%s" successfully added' % reaction2.name
                        print("/dashboard/reactions/%s - Reaction edit success"
                              ) % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print(
                        "/dashboard/reactions/%s - Reaction edit failed: form invalid"
                    ) % rname
                    data['error'] = True
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))
Beispiel #26
0
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #27
0
def modsub_page():
    '''Dashboard Modify Subscription:
    This will allow a user to modify their subscription and account plan
    '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/mod-subscription'
        data['uid'] = user.uid
        tmpl = 'member/mod-subscription.html'
        data['js_bottom'].append('forms/subscribe.js')
        form = []

        # Stripe vs ASM stuff
        if user.payments == "ASM":
            headers = {
                "content-type": "application/json",
                "Authorization": app.config['ASSEMBLY_PRIVATE_KEY']
            }
            paymenturl = app.config['ASSEMBLY_PAYMENTS_URL']
        else:
            from base64 import b64encode
            api_key = b64encode(app.config['STRIPE_PRIVATE_KEY']).decode("ascii")
            headers = {
                "Authorization": "Basic " + api_key,
            }
            paymenturl = app.config['STRIPE_PAYMENTS_URL']

        from generalforms import subscribe
        if data['upgraded'] is False:
            # Upgrade Users
            if request.method == "POST" and \
                    "stripeToken" in request.form and "plan" in request.form:
                stripeToken = request.form['stripeToken']
                plan = request.form['plan']
                if stripeToken:
                    result = None
                    monitor = Monitor()
                    payload = {
                        'email': user.email,
                        'quantity': monitor.count(user.uid, g.rdb_conn),
                        'source': stripeToken,
                        'plan': plan
                    }
                    json_payload = json.dumps(payload)
                    url = paymenturl + "/customers"
                    print ("Making request to %s") % url
                    try:
                        # Send Request to Payment system to create user and subscribe
                        # them to desired plan
                        result = requests.post(
                            url=url, headers=headers,
                            params=payload, verify=True)
                    except:
                        print("Critical Error making request to Payments")
                        flash('There was an error processing \
                              your card details.', 'danger')
                    print("Got {0} status code from Payments".format(
                        result.status_code))
                    if result.status_code >= 200 and result.status_code <= 299:
                        rdata = json.loads(result.text)
                        user.stripeid = rdata['id']
                        user.stripe = stripeToken
                        user.subplans = payload['quantity']
                        user.subscription = payload['plan']
                        if "pro_plus" in plan:
                            user.acttype = "proplus"
                        else:
                            user.acttype = "pro"
                        print("Setting UID %s Subscription to: %s") % (
                            user.uid, user.acttype)
                        subres = user.setSubscription(g.rdb_conn)
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' User Upgrades', 1)
                        if subres:
                            newdata = startData(user)
                            data['limit'] = newdata['limit']
                            data['rlimit'] = newdata['rlimit']
                            data['acttype'] = newdata['acttype']
                            data['subplans'] = newdata['subplans']
                            data['cost'] = newdata['cost']
                            data['subscription'] = newdata['subscription']
                            flash('Subscription successfully created.',
                                  'success')
                        else:
                            flash('Subscription not successfully created.',
                                  'danger')
                    else:
                        flash('Subscription not created got status code: %d' % result.status_code, 'danger')
        # Increase subscription
        if data['upgraded']:
            form = subscribe.AddPackForm(request.form)
            if request.method == "POST" and "stripeToken" not in request.form:
                if form.validate():
                    add_packs = int(form.add_packs.data)
                    # Set subscription quantity to desired monitor count
                    payload = {'quantity': add_packs}
                    json_payload = json.dumps(payload)
                    url = paymenturl + "/customers/" + user.stripeid
                    print("Making request to %s") % url
                    try:
                        # Get Subscription ID
                        result = requests.get(
                            url=url, headers=headers, verify=True)
                        if result.status_code == 200:
                            rdata = json.loads(result.text)
                            subsid = rdata['subscriptions']['data'][0]['id']
                            url = url + "/subscriptions/" + subsid
                            print("Making request to %s") % url
                            # Set Quantity
                            try:
                                if user.payments == "ASM":
                                    result = requests.put(
                                        url=url, headers=headers,
                                        data=json_payload, verify=True)
                                else:
                                    result = requests.post(
                                        url=url, headers=headers,
                                        params=payload, verify=True)
                            except:
                                print("Critical Error making \
                                      request to ASM Payments")
                                flash('An error occured while \
                                      requesting update to %s.' % url, 'danger')
                        else:
                            flash('An error occured while \
                                  pulling subscription details - %d.' % result.status_code, 'danger')
                    except:
                        print("Critical Error making request to ASM Payments")
                        flash('An error occured \
                              while processing the form.', 'danger')
                    print("Got {0} status code from Assembly".format(
                        result.status_code))
                    if result.status_code >= 200 and result.status_code <= 299:
                        user.subplans = add_packs
                        # Save user config
                        print("Setting subscription count to \
                              {0} for user {1}".format(add_packs, user.uid))
                        subres = user.setSubscription(g.rdb_conn)
                        if subres:
                            newdata = startData(user)
                            data['limit'] = newdata['limit']
                            data['rlimit'] = newdata['rlimit']
                            data['acttype'] = newdata['acttype']
                            data['subplans'] = newdata['subplans']
                            data['cost'] = newdata['cost']
                            flash('Subscription successfully modified.',
                                  'success')
                        else:
                            flash('Unknown error modifing subscription.',
                                  'danger')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #28
0
def addcheck_page(cname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/monitors/' + cname
        tmpl = 'monitors/' + cname + '.html'
        data['js_bottom'] = ['monitors/monitorlist.js', 'monitors/base.js', 'monitors/' + cname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__(
                "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            for key in data['reactions'].keys():
                reactchoices.append(
                    (data['reactions'][key]['id'],
                        data['reactions'][key]['name']))
            form.reactions.choices = reactchoices
            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = None
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    monitor.data = tmpdata

                    # Check if the user already exceeds their limit
                    if monitor.count(user.uid, g.rdb_conn) < data['limit']:
                        # Create the monitor if all checks out
                        results = monitor.createMonitor(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/monitors/{0} - \
                              Monitor already exists".format(cname))
                        flash('{0} seems to already exist. \
                              Try using a different name.'.format(
                              monitor.name), 'danger')
                    elif results is False:
                        print("/dashboard/monitors/{0} - \
                            Monitor creation failed".format(cname))
                        flash('Could not create monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        flash('You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                        print("/dashboard/monitors/{0} - \
                              Monitor creation failed: toomany".format(cname))
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added', 1)
                        print("/dashboard/monitors/%s - \
                              Monitor creation successful") % cname
                        flash('Monitor "{0}" successfully added.'.format(
                            monitor.name), 'success')
                        newmonitor = Monitor()
                        newmonitor.get(results, g.rdb_conn)
                        if newmonitor.uid == user.uid:
                            data['monitor'] = {
                                'cid': newmonitor.cid,
                                'name': newmonitor.name,
                                'uid': newmonitor.uid,
                                'ctype': newmonitor.ctype,
                                'url': newmonitor.url,
                                'data': newmonitor.data
                            }
                else:
                    print("/dashboard/monitors/{0} - \
                          Monitor creation failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #29
0
def addcheck_page(cname):
    verify = verifyLogin(app.config['SECRET_KEY'],
                         app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/monitors/' + cname
        tmpl = 'monitors/' + cname + '.html'
        data['js_bottom'] = [
            'monitors/monitorlist.js', 'monitors/base.js',
            'monitors/' + cname + '.js'
        ]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__("monitorforms." + cname, globals(), locals(),
                               ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            for key in data['reactions'].keys():
                reactchoices.append((data['reactions'][key]['id'],
                                     data['reactions'][key]['name']))
            form.reactions.choices = reactchoices
            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = None
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    monitor.data = tmpdata

                    # Check if the user already exceeds their limit
                    if monitor.count(user.uid, g.rdb_conn) < data['limit']:
                        # Create the monitor if all checks out
                        results = monitor.createMonitor(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/monitors/{0} - \
                              Monitor already exists".format(cname))
                        flash(
                            '{0} seems to already exist. \
                              Try using a different name.'.format(
                                monitor.name), 'danger')
                    elif results is False:
                        print("/dashboard/monitors/{0} - \
                            Monitor creation failed".format(cname))
                        flash('Could not create monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        flash(
                            'You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                        print("/dashboard/monitors/{0} - \
                              Monitor creation failed: toomany".format(cname))
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added', 1)
                        print("/dashboard/monitors/%s - \
                              Monitor creation successful") % cname
                        flash(
                            'Monitor "{0}" successfully added.'.format(
                                monitor.name), 'success')
                        newmonitor = Monitor()
                        newmonitor.get(results, g.rdb_conn)
                        if newmonitor.uid == user.uid:
                            data['monitor'] = {
                                'cid': newmonitor.cid,
                                'name': newmonitor.name,
                                'uid': newmonitor.uid,
                                'ctype': newmonitor.ctype,
                                'url': newmonitor.url,
                                'data': newmonitor.data
                            }
                else:
                    print("/dashboard/monitors/{0} - \
                          Monitor creation failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))
Beispiel #30
0
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/' + rname + '.html'
        data['js_bottom'] = ['reactions/base.js', 'reactions/' + rname + '.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        data['msg'] = "This reaction seems to already exist, try using a different name: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction creation failed: exists") % rname
                        data['error'] = True
                    elif results == "edit noexists":
                        data['msg'] = "This reaction can not be edited as it does not exist: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit failed: doesnt exist") % rname
                        data['error'] = True
                    elif results == "edit true":
                        data['msg'] = "Reaction successfully edited: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit successful") % rname
                        data['error'] = False
                    elif results == "edit false":
                        data['msg'] = "Reaction not successfully edited: %s" % reaction.name
                        print("/dashboard/reactions/%s - Reaction edit failed: unknown") % rname
                        data['error'] = True
                    elif results == "toomany":
                        data['msg'] = "Could not create reaction: Too many reactions already created [%d]" % data['rlimit']
                        print("/dashboard/reactions/%s - Reaction creation failed: too many") % rname
                        data['error'] = True
                    elif results is False:
                        data['msg'] = "Could not create reaction"
                        print("/dashboard/reactions/%s - Reaction creation failed: unknown") % rname
                        data['error'] = True
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        data['msg'] = 'Reaction "%s" successfully added' % reaction.name
                        print("/dashboard/reactions/%s - Reaction creation successful") % rname
                        data['error'] = False
                else:
                    data['msg'] = "Form is not valid"
                    print("/dashboard/reactions/%s - Reaction creation failed: form invalid") % rname
                    data['error'] = True

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        return redirect(url_for('user.login_page'))