views.py 24 KB
Newer Older
1
2
from app import app, mail
from flask_mail import Message
Vladislav Rykov's avatar
Vladislav Rykov committed
3

Vladislav Rykov's avatar
Vladislav Rykov committed
4
from flask import render_template, request, redirect, url_for, session, send_from_directory, flash
5
import psycopg2
Vladislav Rykov's avatar
Vladislav Rykov committed
6

Vladislav Rykov's avatar
Vladislav Rykov committed
7
8
9
10
11
import app.dao.user.user as ud
import app.dao.application.application as ad
import app.dao.device.device as dd
import app.dao.pend.pend as pend
import app.dao.data.data as data
Vladislav Rykov's avatar
Vladislav Rykov committed
12
13
import app.dao.notification.notification as nfs
import app.dao.trigger.trigger as tr
Vladislav Rykov's avatar
Vladislav Rykov committed
14
import app.dao.notification_queue.notification_queue as nq
Vladislav Rykov's avatar
Vladislav Rykov committed
15

Vladislav Rykov's avatar
Vladislav Rykov committed
16
import app.helpers.misc as misc
17
import app.helpers.mailer as mailer
Vladislav Rykov's avatar
Vladislav Rykov committed
18

19
import os
Vladislav Rykov's avatar
Vladislav Rykov committed
20
import binascii
Vladislav Rykov's avatar
Vladislav Rykov committed
21

22

23
24
MAX_PG = 5
MAX_PG_ENTRIES_USERS = 10
25
26
MAX_PG_ENTRIES_DATA = 10
MAX_PG_ENTRIES_GRAPH_HOURS = 24
27

Vladislav Rykov's avatar
Vladislav Rykov committed
28
@app.route('/')
29
def index():
Vladislav Rykov's avatar
Vladislav Rykov committed
30
    if 'name' in session and len(session['name']) > 0:
Vladislav Rykov's avatar
Vladislav Rykov committed
31
32
        apps = ad.get_list(session['name'])
        
Vladislav Rykov's avatar
Vladislav Rykov committed
33
        session.pop('appkey', None)
34
        if apps[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
35
            return render_template('old/public/index.html', apps=apps[1], users_signup=app.config['USERS_SIGNUP'])
36
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
37
            return render_template('old/public/index.html', feedback=apps[1], users_signup=app.config['USERS_SIGNUP'])
Vladislav Rykov's avatar
Vladislav Rykov committed
38
    else:
Vladislav Rykov's avatar
Vladislav Rykov committed
39
        return render_template('new/public/login.html', users_signup=app.config['USERS_SIGNUP'])
40
41
42



Vladislav Rykov's avatar
Vladislav Rykov committed
43
@app.route('/register', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
44
def register():
45
    if request.method == 'GET':
Vladislav Rykov's avatar
Vladislav Rykov committed
46
        if 'role' in session and session['role'] == 'admin':
Vladislav Rykov's avatar
Vladislav Rykov committed
47
            return render_template('old/admin/signup.html', users_signup=app.config['USERS_SIGNUP'])
Vladislav Rykov's avatar
Vladislav Rykov committed
48
        else:
49
            if app.config['USERS_SIGNUP']:
Vladislav Rykov's avatar
Vladislav Rykov committed
50
                return render_template('new/public/register.html', users_signup=app.config['USERS_SIGNUP'])
51
            else:
52
                return redirect(url_for('index', users_signup=app.config['USERS_SIGNUP']))
53
    else:
Vladislav Rykov's avatar
Vladislav Rykov committed
54
        if app.config['USERS_SIGNUP'] or ('role' in session and session['role'] == 'admin'):
55
56
57
58
            username = request.form['username']
            password = request.form['password'].encode('utf-8')
            
            if (username == '' or password == ''):
Vladislav Rykov's avatar
Vladislav Rykov committed
59
60
                flash('Username or password fields cannot be empty', 'danger')
                return redirect(url_for('register', users_signup=app.config['USERS_SIGNUP']))
61
62
            elif (len(password) < 8):
                flash('Password length must be at least 8 characters.', 'danger')
Vladislav Rykov's avatar
Vladislav Rykov committed
63
                return redirect(url_for('register', users_signup=app.config['USERS_SIGNUP']))
Vladislav Rykov's avatar
Vladislav Rykov committed
64
            else:
65
                role = 'user'
Vladislav Rykov's avatar
Vladislav Rykov committed
66
                if 'role' in request.form and request.form['role'] == 'administrator':
67
68
69
70
71
72
                    role = 'admin'

                res = ud.create(username, password, role)
                if (not res[0]):
                    flash('Error: {}'.format(res[1]), 'danger')
                    return redirect(request.url)
Vladislav Rykov's avatar
Vladislav Rykov committed
73
                else:
74
75
76
                    session['name'] = username
                    
                    flash('User successfully created.', 'success')
77

Vladislav Rykov's avatar
Vladislav Rykov committed
78
                    if 'role' in session and session['role'] == 'admin':
79
80
81
82
83
                        return redirect(url_for('dashboard'))
                    else:
                        return redirect(url_for('index'))
        else:
            return redirect(url_for('index'))
84
85


Vladislav Rykov's avatar
Vladislav Rykov committed
86
@app.route('/login', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
87
def login():
Vladislav Rykov's avatar
Vladislav Rykov committed
88
    if request.method == 'GET':
Vladislav Rykov's avatar
Vladislav Rykov committed
89
        return render_template('new/public/login.html')
Vladislav Rykov's avatar
Vladislav Rykov committed
90
91
    else: 
        username = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
92
        password = request.form['password'].encode('utf-8')
Vladislav Rykov's avatar
Vladislav Rykov committed
93
94

        if (username == '' or password == ''):
Vladislav Rykov's avatar
Vladislav Rykov committed
95
96
            flash('Username or password fields cannot be empty', 'danger')
            return redirect(request.url)
Vladislav Rykov's avatar
Vladislav Rykov committed
97
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
98
            res = ud.check(username, password)
Vladislav Rykov's avatar
Vladislav Rykov committed
99
            if (not res[0]):
Vladislav Rykov's avatar
Vladislav Rykov committed
100
101
                flash('Error: {}'.format(res[1]), 'danger')
                return redirect(request.url)
Vladislav Rykov's avatar
Vladislav Rykov committed
102
103
            else:
                session['name'] = username
104
                session['role'] = res[1][2]
Vladislav Rykov's avatar
Vladislav Rykov committed
105
        
Vladislav Rykov's avatar
Vladislav Rykov committed
106
107
108
                return redirect(url_for('index'))


109

Vladislav Rykov's avatar
Vladislav Rykov committed
110
@app.route('/logout')
Vladislav Rykov's avatar
Vladislav Rykov committed
111
112
113
def logout():
    session.clear()
    return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
114
115


116

Vladislav Rykov's avatar
Vladislav Rykov committed
117
@app.route('/new-app')
118
def new_application():
Vladislav Rykov's avatar
Vladislav Rykov committed
119
    if 'name' in session:
Vladislav Rykov's avatar
Vladislav Rykov committed
120
        return render_template('old/public/new-app.html')
Vladislav Rykov's avatar
Vladislav Rykov committed
121
122
    else:
        return redirect(url_for('index'))
123
124
125



Vladislav Rykov's avatar
Vladislav Rykov committed
126
127
@app.route('/app', methods=['GET', 'POST'])
def app_():
Vladislav Rykov's avatar
Vladislav Rykov committed
128
129
130
    if 'name' in session:
        if request.method == 'GET':
            session['appkey'] = request.args.get('appkey')
Vladislav Rykov's avatar
Vladislav Rykov committed
131

Vladislav Rykov's avatar
Vladislav Rykov committed
132
133
            ap = ad.get(session['appkey'])
            devs = dd.get_list(ap[1][1])
134
135

            session['appname'] = ap[1][0]
136
137
            
            if session['role'] == 'admin' or session['name'] == ap[1][2]:
Vladislav Rykov's avatar
Vladislav Rykov committed
138
                return render_template('old/public/app.html', app=ap[1], devs=devs[1])
139
140
            else:
                return redirect(url_for('index'))
141
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
142
143
            if request.form['appname'] == '':
                error = 'Application name cannot be empty.'
Vladislav Rykov's avatar
Vladislav Rykov committed
144
                return render_template('old/public/new-app.html', feedback=error)
Vladislav Rykov's avatar
Vladislav Rykov committed
145
            else:
Vladislav Rykov's avatar
Vladislav Rykov committed
146
                appkey = misc.rand_str(app.config['APPKEY_LENGTH']).decode('utf-8')
147
148
149
150
151
152
153
                secure_key = misc.gen_skey_b64(16)
                secure = False

                if request.form.getlist('secure') and request.form.getlist('secure')[0] == 'true':
                    secure = True

                res = ad.create(request.form['appname'], appkey, session['name'], request.form['appdesc'], secure, secure_key)
Vladislav Rykov's avatar
Vladislav Rykov committed
154
            
Vladislav Rykov's avatar
Vladislav Rykov committed
155
                if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
156
                    return render_template('old/public/new-app.html', feedback=res[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
157
            
Vladislav Rykov's avatar
Vladislav Rykov committed
158
                res = dd.create_table(appkey)
159
            
Vladislav Rykov's avatar
Vladislav Rykov committed
160
                if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
161
                    ad.delete(appkey)
Vladislav Rykov's avatar
Vladislav Rykov committed
162
                    return render_template('old/public/new-app.html', feedback=res[1])
163
            
Vladislav Rykov's avatar
Vladislav Rykov committed
164
165
166
                return redirect(url_for('index'))
    else:
        return redirect(url_for('index'))
167

Vladislav Rykov's avatar
Vladislav Rykov committed
168
@app.route('/delete-app')
169
def delete_app():
Vladislav Rykov's avatar
Vladislav Rykov committed
170
    if 'name' in session:
Vladislav Rykov's avatar
Vladislav Rykov committed
171
        devs = dd.get_list(session['appkey'])
172
    
Vladislav Rykov's avatar
Vladislav Rykov committed
173
174
        for dev in devs[1]:
            data.delete_table(session['appkey'], dev[1])
175
    
Vladislav Rykov's avatar
Vladislav Rykov committed
176
        dd.delete_table(session['appkey'])
177
    
Vladislav Rykov's avatar
Vladislav Rykov committed
178
        res = ad.delete(session['appkey'])
179
    
Vladislav Rykov's avatar
Vladislav Rykov committed
180
        if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
181
            return redirect(url_for('app_'))
Vladislav Rykov's avatar
Vladislav Rykov committed
182
183
        else:
            return redirect(url_for('index'))
184
185
    else:
        return redirect(url_for('index'))
186

Vladislav Rykov's avatar
Vladislav Rykov committed
187

Vladislav Rykov's avatar
Vladislav Rykov committed
188
@app.route('/add-dev')
Vladislav Rykov's avatar
Vladislav Rykov committed
189
def new_dev():
Vladislav Rykov's avatar
Vladislav Rykov committed
190
    if 'name' in session:
Vladislav Rykov's avatar
Vladislav Rykov committed
191
        dev_list = dd.get_list(session['appkey'])
Vladislav Rykov's avatar
Vladislav Rykov committed
192
    
Vladislav Rykov's avatar
Vladislav Rykov committed
193
        if not dev_list[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
194
            return render_template('old/public/add-dev.html', feedback=dev_list[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
195
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
196
            return render_template('old/public/add-dev.html', free_ids=misc.prep_id_range(dev_list[1]))
Vladislav Rykov's avatar
Vladislav Rykov committed
197
    else:
Vladislav Rykov's avatar
Vladislav Rykov committed
198
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
199
200
201
 


Vladislav Rykov's avatar
Vladislav Rykov committed
202
@app.route('/dev', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
203
def dev():
Vladislav Rykov's avatar
Vladislav Rykov committed
204
205
    if 'name' in session:
        if request.method == 'GET':
206
207
208
209
210
211
            ap = ad.get(session['appkey'])
            if session['role'] == 'admin' or session['name'] == ap[1][2]:
                dev = dd.get(session['appkey'], request.args.get('id'))

                session['devid'] = int(dev[1][1])
                session['devname'] = dev[1][0]
Vladislav Rykov's avatar
Vladislav Rykov committed
212
        
213
                last = data.get_last_n(session['appkey'], session['devid'], 1)
Vladislav Rykov's avatar
Vladislav Rykov committed
214
        
215
                ltup = 'Device have not sent data yet'
Vladislav Rykov's avatar
Vladislav Rykov committed
216

217
218
                if last[0]:
                    ltup = last[1][0][1]
219

Vladislav Rykov's avatar
Vladislav Rykov committed
220
                return render_template('old/public/dev.html', dev=dev[1], appkey=session['appkey'], ltup=ltup)
221
222
            else:
                return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
223
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
224
            res = dd.create(request.form['devname'], request.form['devid'], session['appkey'], request.form['devdesc'])
Vladislav Rykov's avatar
Vladislav Rykov committed
225

226
            if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
227
                return render_template('old/public/add-dev.html', feedback=res[1])
228
            else:
Vladislav Rykov's avatar
Vladislav Rykov committed
229
230
231
                res = data.create_table(session['appkey'], request.form['devid'])
            
                if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
232
                    dd.delete(session['appkey'], request.form['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
233
                    return render_template('old/public/add-dev.html', feedback=res[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
234
                else:
235
                    return redirect(url_for('app_', appkey=session['appkey']))
Vladislav Rykov's avatar
Vladislav Rykov committed
236
237
    else:
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
238
239


Vladislav Rykov's avatar
Vladislav Rykov committed
240
@app.route('/dev-conf', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
241
def dev_conf():
Vladislav Rykov's avatar
Vladislav Rykov committed
242
243
    if 'name' in session and 'devid' in session:
        if request.method == 'GET':
244
245
246
247
248
249
250
251
252
253
254
255
            pend_msgs = pend.get_list(session['appkey'], session['devid'])
            
            if pend_msgs[0]:
                config_list = []

                for pm in pend_msgs[1]:
                    cntt = binascii.a2b_base64(pm[2])
                    config_id = int(cntt[0])
                    config_args = cntt[2:(len(cntt)-1)].decode('utf-8')
                    ack = pm[3]
                    config_list.append((config_id, config_args, ack, pm[2]))

Vladislav Rykov's avatar
Vladislav Rykov committed
256
                return render_template('old/public/dev-conf.html', devname=session['devname'], config_list=config_list)
257
            else:
Vladislav Rykov's avatar
Vladislav Rykov committed
258
                return render_template('old/public/dev-conf.html', devname=session['devname'])
Vladislav Rykov's avatar
Vladislav Rykov committed
259
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
260
            base64_args = pend_base64_encode(request.form['arg'], request.form['confid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
261
            pend.create(session['appkey'], session['devid'], base64_args)
Vladislav Rykov's avatar
Vladislav Rykov committed
262

Vladislav Rykov's avatar
Vladislav Rykov committed
263
264
265
            return redirect(url_for('dev', id=session['devid']))
    else:
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
266

267
268
269
270
271
272
273
274
275
276
277
278
279
@app.route('/dev-conf-rm')
def dev_conf_rm():
    if 'name' in session and 'appkey' in session and 'devid' in session:
        res = pend.delete(session['appkey'], session['devid'], request.args.get('conf')+'_')

        if res[0]:
            flash('Configuration message successfully removed.','success')
            return redirect(url_for('dev_conf'))
        else:
            flash('Error removing configuration message: {}'.format(res[1]), 'danger')
            return redirect(url_for('dev_conf'))
    else:
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
280

Vladislav Rykov's avatar
Vladislav Rykov committed
281

Vladislav Rykov's avatar
Vladislav Rykov committed
282
@app.route('/delete-dev')
Vladislav Rykov's avatar
Vladislav Rykov committed
283
def delete_dev():
Vladislav Rykov's avatar
Vladislav Rykov committed
284
285
    if 'name' in session and 'devid' in session:
        data.delete_table(session['appkey'], session['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
286
        res = dd.delete(session['appkey'], session['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
287

Vladislav Rykov's avatar
Vladislav Rykov committed
288
        return redirect(url_for('app_', appkey=session['appkey']))
Vladislav Rykov's avatar
Vladislav Rykov committed
289
290
    else:
        return redirect(utl_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
291
292


Vladislav Rykov's avatar
Vladislav Rykov committed
293
@app.route('/dev-data')
294
295
296
297
298
299
300
301
302
303
def dev_data_pg():
    if 'name' in session and 'devid' in session:
        cur_pg = 1
        if request.args.get('p'):
            cur_pg = int(request.args.get('p'))
            if cur_pg < 1:
                cur_pg = 1
        
        last = data.get_last_range(session['appkey'], session['devid'], [MAX_PG_ENTRIES_DATA, (cur_pg-1)*MAX_PG_ENTRIES_DATA])
        
Vladislav Rykov's avatar
Vladislav Rykov committed
304
305
306
307
        ent_cnt = data.get_count(session['appkey'], session['devid'])
        if ent_cnt[0]:
            # range data
            rd = misc.paging(cur_pg, ent_cnt[1][0], MAX_PG_ENTRIES_DATA, MAX_PG)
308

Vladislav Rykov's avatar
Vladislav Rykov committed
309
            if ent_cnt[1][0] > 0:
Vladislav Rykov's avatar
Vladislav Rykov committed
310
                return render_template('old/public/dev-data-t.html', data=last[1], total=ent_cnt[1][0], cp=cur_pg, np=rd[2], pp=rd[0], pr=rd[1], devname=session['devname'])
Vladislav Rykov's avatar
Vladislav Rykov committed
311
            else:
Vladislav Rykov's avatar
Vladislav Rykov committed
312
                return render_template('old/public/dev-data-t.html', devname=session['devname'])
313
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
314
            flash('Error: {}'.format(ent_cnt[1]), 'danger')
Vladislav Rykov's avatar
Vladislav Rykov committed
315
            return render_template('old/public/dev-data-t.html', devname=session['devname'])
316
317
318
319
    else:
        return redirect(utl_for('index'))


Vladislav Rykov's avatar
Vladislav Rykov committed
320
321
322
323
324
@app.route('/dev-vars')
def dev_vars():
    if 'name' in session:
        last = data.get_last_n(session['appkey'], request.args.get('id'), 1)
        if last[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
325
            select = '<select class="form-control notifelem" id="varname" name="varname" onchange="onvar(event)" required>'
Vladislav Rykov's avatar
Vladislav Rykov committed
326
327
328
329
330
331
332
333
            select += '<option value="-">Select Variable</option>'
            for k in last[1][0][2]:
                select += '<option>'+k+'</option>'
            select += '</select>'
            return select
    else:
        return redirect(url_for('index'))

334

Vladislav Rykov's avatar
Vladislav Rykov committed
335
@app.route('/data-csv')
Vladislav Rykov's avatar
Vladislav Rykov committed
336
def data_csv():
Vladislav Rykov's avatar
Vladislav Rykov committed
337
338
    if 'name' in session and 'devid' in session:
        dumpd = data.get_all(session['appkey'], session['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
339

Vladislav Rykov's avatar
Vladislav Rykov committed
340
        fn = session['appkey']+ '_' +str(session['devid'])+ '.csv'
Vladislav Rykov's avatar
Vladislav Rykov committed
341

342
        with open(app.config['DATA_DOWNLOAD_DIR_OS']+'/'+fn, 'w+') as f: 
Vladislav Rykov's avatar
Vladislav Rykov committed
343
            f.write('utc,timestamp,')
Vladislav Rykov's avatar
Vladislav Rykov committed
344
345
            for d in dumpd[1][0][2]:
                f.write(d)
Vladislav Rykov's avatar
Vladislav Rykov committed
346
347
                f.write(',')
            f.write('\n')
Vladislav Rykov's avatar
Vladislav Rykov committed
348
349
        
            for row in dumpd[1]:
Vladislav Rykov's avatar
Vladislav Rykov committed
350
                f.write('{},{},'.format(row[0],row[1]))
Vladislav Rykov's avatar
Vladislav Rykov committed
351
352
353
354
                for v in row[2]:
                    f.write(str(row[2][v]))
                    f.write(',')
                f.write('\n')
Vladislav Rykov's avatar
Vladislav Rykov committed
355
    
Vladislav Rykov's avatar
Vladislav Rykov committed
356
        return send_from_directory(app.config['DATA_DOWNLOAD_DIR'], fn, as_attachment=True)
Vladislav Rykov's avatar
Vladislav Rykov committed
357
358
    else:
        return redirect(utl_for('index'))
359
360


Vladislav Rykov's avatar
Vladislav Rykov committed
361
362
363
364
365
366
367
368
369
370
371
372
373
@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
    if 'role' in session and session['role'] == 'admin':
        user_cnt = ud.get_count()
        apps_cnt = ad.get_count()
        devs_cnt = dd.get_count_all()

        cur_pg = 1
        if request.args.get('p'):
            cur_pg = int(request.args.get('p'))
            if cur_pg < 1:
                cur_pg = 1

Vladislav Rykov's avatar
Vladislav Rykov committed
374
        users = None
Vladislav Rykov's avatar
Vladislav Rykov committed
375
        
Vladislav Rykov's avatar
Vladislav Rykov committed
376
377
        if request.method == 'POST':
            session['users_filter'] = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
378
            
Vladislav Rykov's avatar
Vladislav Rykov committed
379
380
381
        if 'users_filter' in session:
            users = ud.get_range_name(session['users_filter'], [MAX_PG_ENTRIES_USERS, (cur_pg-1)*MAX_PG_ENTRIES_USERS])
            rd = misc.paging(cur_pg, len(users[1]), MAX_PG_ENTRIES_USERS, MAX_PG)
Vladislav Rykov's avatar
Vladislav Rykov committed
382
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
383
384
385
            users = ud.get_range([MAX_PG_ENTRIES_USERS, (cur_pg-1)*MAX_PG_ENTRIES_USERS])
            rd = misc.paging(cur_pg, user_cnt[1][0], MAX_PG_ENTRIES_USERS, MAX_PG)
        
Vladislav Rykov's avatar
Vladislav Rykov committed
386
        return render_template('old/admin/dashboard.html', users_cnt=user_cnt[1][0], apps_cnt=apps_cnt[1][0], dev_cnt=devs_cnt, users=users[1], pp=rd[0], pr=rd[1], np=rd[2], cp=cur_pg, usn=(cur_pg-1)*MAX_PG_ENTRIES_USERS+1)
Vladislav Rykov's avatar
Vladislav Rykov committed
387
388
389
    else:
        return redirect(url_for('index'))

Vladislav Rykov's avatar
Vladislav Rykov committed
390
391
392
393
394
395
396

@app.route('/dashboard-clean-search')
def dashboard_clean_search():
    if 'users_filter' in session:
        session.pop('users_filter', None)
    return redirect(url_for('dashboard'))

397
398
399
400
401
402
403
404
405

@app.route('/user')
def user():
    if 'role' in session and session['role'] == 'admin':
        name = request.args.get('name')
        apps = ad.get_list(name)
        
        session.pop('appkey', None)
        if apps[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
406
            return render_template('old/admin/user.html', apps=apps[1], username=name)
407
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
408
            return render_template('old/admin/user.html', feedback=apps[1], username=name)
409
    else:
Vladislav Rykov's avatar
Vladislav Rykov committed
410
        return render_template('old/public/index.html')
411
412
413
414
415


@app.route('/user-delete')
def user_delete():
    user = ud.get(request.args.get('name'))
Vladislav Rykov's avatar
Vladislav Rykov committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    if user[0] and user[1][2] != 'admin' and session['role'] == 'admin':
        app_list = ad.get_list(user[1][0])

        res = (True,)
        if app_list[0]:
            for app in app_list[1]:
                devs = dd.get_list(app[1])
                for dev in devs[1]:
                    res = data.delete_table(app[1], dev[1])
                    if not res[0]:
                        break
    
                if res[0]:
                    res = dd.delete_table(app[1])
                    
                if res[0]:
                    res = ad.delete(app[1])

                if not res[0]:
                    break

        if res[0]:
            res = ud.delete(user[1][0])

        if not res[0]:
            flash('Error: {}'.format(res[1]), 'danger')
Vladislav Rykov's avatar
Vladislav Rykov committed
442
            return render_template('old/admin/user.html', username=user[1][0])
Vladislav Rykov's avatar
Vladislav Rykov committed
443
444
445
446
447
        else:
                return redirect(url_for('dashboard'))
    else:
        flash('Warning: the user is admin or does not exist.' ,'warning')
        return redirect(url_for('index'))
448

Vladislav Rykov's avatar
Vladislav Rykov committed
449

450
451
452
453
@app.route('/settings', methods=['GET', 'POST'])
def settings():
    if request.method == 'GET':
        if session['role'] == 'admin':
Vladislav Rykov's avatar
Vladislav Rykov committed
454
            return render_template('old/admin/settings.html', username=session['name'], users_signup=app.config['USERS_SIGNUP'])
455
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
456
            return render_template('old/public/settings.html', username=session['name'])
457
458
459
460
461
462
463
464
465
466
467
468
    else:
        if request.form['name'] != session['name']:
            res = ud.update_name(session['name'], request.form['name'])
            if not res[0]:
                flash('Error: {}'.format(res[1]), 'danger')
                return redirect(request.url);
            else:
                session['name'] = request.form['name']
        if request.form['password'] != '':
            res = ud.update_password(session['name'], request.form['password'].encode('utf-8'))
            if not res[0]:
                flash('Error: {}'.format(res[1]), 'danger')
469
470
471
472
473
474
                return redirect(request.url)
        if session['role'] == 'admin':
            if request.form.getlist('users_signup') and request.form.getlist('users_signup')[0] == 'us':
                app.config['USERS_SIGNUP'] = True
            else:
                app.config['USERS_SIGNUP'] = False
475
476


477
        return redirect(request.url)
478
479


480
481
@app.route('/dev-data/<var>/<dest>/<page>')
def dev_data(var, dest, page):
482
    if dest == 'graph':
483
        last = data.get_last_hours(session['appkey'], session['devid'], MAX_PG_ENTRIES_GRAPH_HOURS, int(page))
484
485
486
487
488
489
490
491
        arr = '[["Time", "{}"],'.format(var)
        if last[0]:
            for d in last[1]:
                arr += '[new Date('+str(d[0])+'*1000),'+str(d[2][var])+'],'
            arr += ']'
        return arr
    elif dest == 'table':
        # for table <cnt> is in items
492
        last = data.get_last_range(session['appkey'], session['devid'], [MAX_PG_ENTRIES_DATA, (int(page)-1)*MAX_PG_ENTRIES_DATA])
493
494
495
496
497
498
499
        #t = """ <thead>
        #            <th>Time</th>
        #            <th>{}</th>
        #        </thead>
        #        <tbody>
        #""".format(var)
        t = ''
500
501
502
        if last[0]:
            for d in last[1]:
                t += '<tr><th>'+d[1]+'</th><th>'+str(d[2][var])+'</th></tr>'
503
        #t += '</tbody>'
504
        return t
505
506


Vladislav Rykov's avatar
Vladislav Rykov committed
507
508
509
@app.route('/alerts')
def alerts():
    if 'name' in session:
510
        alerts = nfs.get_alerts_list(session['appkey'])
Vladislav Rykov's avatar
Vladislav Rykov committed
511
        return render_template('old/public/alerts.html', alert_list=alerts[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
512
513
514
515
516
517
518
    else:
        return redirect(url_for('index'))

@app.route('/new-alert')
def new_alert():
    if 'name' in session:
        devs = dd.get_list(session['appkey'])
Vladislav Rykov's avatar
Vladislav Rykov committed
519
        return render_template('old/public/new-alert.html', devs=devs[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
520
521
522
523
524
525
    else:
        return redirect(url_for('index'))


@app.route('/alert', methods=['POST'])
def alert():
526
527
528
529
530
    if 'name' in session:
        if request.method == 'POST':
            # create new notification
            nid = misc.rand_str(app.config['NID_LENGTH']).decode('utf-8')
            dev = dd.get(session['appkey'], request.form['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
            
            try:
                desc = dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue']
                res = nfs.create(nid, session['appkey'], request.form['devid'], request.form['alertname'], desc, 'alert', request.form['alertemail'])
                if res[0]:
                    # create new function and trigger
                    tr.create_function(session['appkey'], request.form['devid'], nid, [request.form['varname'],request.form['operation'],request.form['avalue']])
                    tr.create(session['appkey'], request.form['devid'], nid)
                    return redirect(url_for('alerts'))
                else:
                    flash('Error creating new alert: {}'.format(res[1]), 'danger')
                    return redirect(url_for('alerts'))
            except Exception as e:
                flash('Error creating new alert: {}. Make sure you have filled all form fields.'.format(e), 'danger')
                return redirect(url_for('new_alert'))
546
547
548
549
        else:
            return redirect(url_for('index'))
    else:
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
550
551
552
553

@app.route('/alert-rm')
def alarm_rm():
    if 'name' in session:
Vladislav Rykov's avatar
Vladislav Rykov committed
554
        nq.delete(session['appkey'], request.args.get('devid'), request.args.get('id'))
Vladislav Rykov's avatar
Vladislav Rykov committed
555
556
        tr.delete(session['appkey'], request.args.get('devid'), request.args.get('id'))
        tr.delete_function(session['appkey'], request.args.get('devid'), request.args.get('id'))
557
        res = nfs.delete(session['appkey'], request.args.get('devid'), request.args.get('id'))
Vladislav Rykov's avatar
Vladislav Rykov committed
558
559

        if res[0]:
560
            flash('Alert removed', 'success')
Vladislav Rykov's avatar
Vladislav Rykov committed
561
562
            return redirect(url_for('alerts'))
        else:
563
            flash('Alert cannot be removed : {}'.format(res[1]), 'danger')
Vladislav Rykov's avatar
Vladislav Rykov committed
564
            return redirect(url_for('alerts'))
Vladislav Rykov's avatar
Vladislav Rykov committed
565
566
567
    else:
        return redirect(url_for('index'))

568
569
570
571
572
573

@app.route('/automation', methods=['GET','POST'])
def automation():
    if 'name' in session:
        if request.method == 'GET':
            auto = nfs.get_automation_list(session['appkey'])
Vladislav Rykov's avatar
Vladislav Rykov committed
574
            return render_template('old/public/automation.html', auto_list=auto[1])
575
576
        elif request.method == 'POST':
            # new automation
Vladislav Rykov's avatar
Vladislav Rykov committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
            nid = misc.rand_str(app.config['NID_LENGTH']).decode('utf-8')
            dev = dd.get(session['appkey'], request.form['devid'])
            adev = dd.get(session['appkey'], request.form['adevid'])
            try:
                desc = 'IF '+dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue']+' THEN '+adev[1][0]+'.confID_'+request.form['confid']+' = '+request.form['arg']
                # action format: '<devid>#<confid>#<arg>'
                action = request.form['adevid']+'#'+request.form['confid']+'#'+request.form['arg']
                res = nfs.create(nid, session['appkey'], request.form['devid'], request.form['automationname'], desc, 'automation', action)
                if res[0]:
                    # create new function and trigger
                    tr.create_function(session['appkey'], request.form['devid'], nid, [request.form['varname'],request.form['operation'],request.form['avalue']])
                    tr.create(session['appkey'], request.form['devid'], nid)
                    return redirect(url_for('automation'))
                else:
                    flash('Error creating new alert: {}'.format(res[1]), 'danger')
                    return redirect(url_for('automation'))
            
                return redirect(url_for('autmation'))
            except Exception as e:
                flash('Error creating new automation: {}. Make sure you have filled all form fields correctly.'.format(e), 'danger')
                return redirect(url_for('automation'))

599
600
601
602
603
604
605
606
    else:
        return redirect(url_for('index'))


@app.route('/new-automation')
def new_automation():
    if 'name' in session:
        devs = dd.get_list(session['appkey'])
Vladislav Rykov's avatar
Vladislav Rykov committed
607
        return render_template('old/public/new-automation.html', devs=devs[1])
608
609
610
611
    else:
        return redirect(url_for('index'))


Vladislav Rykov's avatar
Vladislav Rykov committed
612
@app.route('/automation-rm')
Vladislav Rykov's avatar
Vladislav Rykov committed
613
def automation_rm():
Vladislav Rykov's avatar
Vladislav Rykov committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
    if 'name' in session:
        nq.delete(session['appkey'], request.args.get('devid'), request.args.get('id'))
        tr.delete(session['appkey'], request.args.get('devid'), request.args.get('id'))
        tr.delete_function(session['appkey'], request.args.get('devid'), request.args.get('id'))
        res = nfs.delete(session['appkey'], request.args.get('devid'), request.args.get('id'))

        if res[0]:
            flash('Automation removed', 'success')
            return redirect(url_for('alerts'))
        else:
            flash('Automation cannot be removed : {}'.format(res[1]), 'danger')
            return redirect(url_for('alerts'))
    else:
        return redirect(url_for('index'))




632
633
def pend_delete_all_ack():
    pend.delete_all_ack()
Vladislav Rykov's avatar
Vladislav Rykov committed
634

635
636
637
638
639
640
641
642
643
def fire_notifications(app):
    fnfs = nq.get_all()
    if fnfs[0]:
        for fnf in fnfs[1]:
            nf = nfs.get(fnf[1], fnf[2], fnf[0])
            if nf[1][5] == 'alert':
                # send mail
                mailer.send_mail(app, nf[1], fnf)
            elif nf[1][5] == 'automation':
Vladislav Rykov's avatar
Vladislav Rykov committed
644
645
646
647
648
649
                # enqueue confid
                # action format: '<devid>#<confid>#<arg>'
                action = nf[1][6].split('#')
                base64_args = misc.pend_base64_encode(action[2], action[1])
                pend.create(nf[1][1], action[0], base64_args)
            nq.delete(fnf[1], fnf[2], fnf[0])