views.py 20.9 KB
Newer Older
Vladislav Rykov's avatar
Vladislav Rykov committed
1
from app import app
Vladislav Rykov's avatar
Vladislav Rykov committed
2
from flask_mail import Mail, 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
Vladislav Rykov's avatar
Vladislav Rykov committed
5
from flask_mail import Message
6
import psycopg2
Vladislav Rykov's avatar
Vladislav Rykov committed
7

Vladislav Rykov's avatar
Vladislav Rykov committed
8
9
10
11
12
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
13
14
import app.dao.notification.notification as nfs
import app.dao.trigger.trigger as tr
Vladislav Rykov's avatar
Vladislav Rykov committed
15
import app.dao.notification_queue.notification_queue as nq
Vladislav Rykov's avatar
Vladislav Rykov committed
16

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

19
import binascii
20
import os
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
mail = Mail(app)
29

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



Vladislav Rykov's avatar
Vladislav Rykov committed
46
@app.route('/signup', methods=['GET', 'POST'])
47
48
def signup():
    if request.method == 'GET':
Vladislav Rykov's avatar
Vladislav Rykov committed
49
        if session['role'] and session['role'] == 'admin':
50
            return render_template('admin/signup.html', users_signup=app.config['USERS_SIGNUP'])
Vladislav Rykov's avatar
Vladislav Rykov committed
51
        else:
52
            if app.config['USERS_SIGNUP']:
53
                return render_template('public/signup.html', users_signup=app.config['USERS_SIGNUP'])
54
            else:
55
                return redirect(url_for('index', users_signup=app.config['USERS_SIGNUP']))
56
57
58
59
60
61
62
    else:
        if app.config['USERS_SIGNUP'] or session['role'] == 'admin':
            username = request.form['username']
            password = request.form['password'].encode('utf-8')
            
            if (username == '' or password == ''):
                feedback = 'Username or password fields cannot be empty'
63
                return render_template('public/signup.html', feedback=feedback, users_signup=app.config['USERS_SIGNUP'])
64
65
            elif (len(password) < 8):
                flash('Password length must be at least 8 characters.', 'danger')
66
                return redirect(request.url, users_signup=app.config['USERS_SIGNUP'])
Vladislav Rykov's avatar
Vladislav Rykov committed
67
            else:
68
69
70
71
72
73
74
75
                role = 'user'
                if request.form['role'] and request.form['role'] == 'administrator':
                    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
76
                else:
77
78
79
                    session['name'] = username
                    
                    flash('User successfully created.', 'success')
80

81
82
83
84
85
86
                    if session['role'] and session['role'] == 'admin':
                        return redirect(url_for('dashboard'))
                    else:
                        return redirect(url_for('index'))
        else:
            return redirect(url_for('index'))
87
88


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

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


112

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


119

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



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

Vladislav Rykov's avatar
Vladislav Rykov committed
135
136
            ap = ad.get(session['appkey'])
            devs = dd.get_list(ap[1][1])
137
138

            session['appname'] = ap[1][0]
139
140
141
142
143
            
            if session['role'] == 'admin' or session['name'] == ap[1][2]:
                return render_template('public/app.html', app=ap[1], devs=devs[1])
            else:
                return redirect(url_for('index'))
144
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
145
146
            if request.form['appname'] == '':
                error = 'Application name cannot be empty.'
Vladislav Rykov's avatar
Vladislav Rykov committed
147
                return render_template('public/new-app.html', feedback=error)
Vladislav Rykov's avatar
Vladislav Rykov committed
148
            else:
Vladislav Rykov's avatar
Vladislav Rykov committed
149
                appkey = misc.rand_str(app.config['APPKEY_LENGTH']).decode('utf-8')
Vladislav Rykov's avatar
Vladislav Rykov committed
150
                res = ad.create(request.form['appname'], appkey, session['name'], request.form['appdesc'])
Vladislav Rykov's avatar
Vladislav Rykov committed
151
            
Vladislav Rykov's avatar
Vladislav Rykov committed
152
                if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
153
                    return render_template('public/new-app.html', feedback=res[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
154
            
Vladislav Rykov's avatar
Vladislav Rykov committed
155
                res = dd.create_table(appkey)
156
            
Vladislav Rykov's avatar
Vladislav Rykov committed
157
                if not res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
158
                    ad.delete(appkey)
Vladislav Rykov's avatar
Vladislav Rykov committed
159
                    return render_template('public/new-app.html', feedback=res[1])
160
            
Vladislav Rykov's avatar
Vladislav Rykov committed
161
162
163
                return redirect(url_for('index'))
    else:
        return redirect(url_for('index'))
164

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

Vladislav Rykov's avatar
Vladislav Rykov committed
184

Vladislav Rykov's avatar
Vladislav Rykov committed
185
@app.route('/add-dev')
Vladislav Rykov's avatar
Vladislav Rykov committed
186
def new_dev():
Vladislav Rykov's avatar
Vladislav Rykov committed
187
    if 'name' in session:
Vladislav Rykov's avatar
Vladislav Rykov committed
188
        dev_list = dd.get_list(session['appkey'])
Vladislav Rykov's avatar
Vladislav Rykov committed
189
    
Vladislav Rykov's avatar
Vladislav Rykov committed
190
    #print('dev list : ', dev_list)
Vladislav Rykov's avatar
Vladislav Rykov committed
191

Vladislav Rykov's avatar
Vladislav Rykov committed
192
        if not dev_list[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
193
            return render_template('public/add-dev.html', feedback=dev_list[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
194
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
195
            return render_template('public/add-dev.html', free_ids=misc.prep_id_range(dev_list[1]))
Vladislav Rykov's avatar
Vladislav Rykov committed
196
    else:
Vladislav Rykov's avatar
Vladislav Rykov committed
197
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
198
199
200
 


Vladislav Rykov's avatar
Vladislav Rykov committed
201
@app.route('/dev', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
202
def dev():
Vladislav Rykov's avatar
Vladislav Rykov committed
203
204
    if 'name' in session:
        if request.method == 'GET':
205
206
207
208
209
210
            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
211
        
212
                last = data.get_last_n(session['appkey'], session['devid'], 1)
Vladislav Rykov's avatar
Vladislav Rykov committed
213
        
214
                ltup = 'Device have not sent data yet'
Vladislav Rykov's avatar
Vladislav Rykov committed
215

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

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

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


Vladislav Rykov's avatar
Vladislav Rykov committed
239
@app.route('/dev-conf', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
240
def dev_conf():
Vladislav Rykov's avatar
Vladislav Rykov committed
241
242
    if 'name' in session and 'devid' in session:
        if request.method == 'GET':
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
            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]))

                return render_template('public/dev-conf.html', devname=session['devname'], config_list=config_list)
            else:
                return render_template('public/dev-conf.html', devname=session['devname'])
Vladislav Rykov's avatar
Vladislav Rykov committed
258
259
260
261
262
        else:
            argslen = len(request.form['arg']) + 1
            args = bytearray(argslen + 2)
            args[0] = int(request.form['confid'])
            args[1] = argslen
Vladislav Rykov's avatar
Vladislav Rykov committed
263
        
264
            bstr = bytes(request.form['arg'].encode('utf-8'))
Vladislav Rykov's avatar
Vladislav Rykov committed
265
266
267
268
            i = 0
            while i < argslen - 1:
                args[2+i] = bstr[i]
                i += 1
Vladislav Rykov's avatar
Vladislav Rykov committed
269

Vladislav Rykov's avatar
Vladislav Rykov committed
270
            base64_args = binascii.b2a_base64(args).decode('utf-8')
Vladislav Rykov's avatar
Vladislav Rykov committed
271

Vladislav Rykov's avatar
Vladislav Rykov committed
272
            pend.create(session['appkey'], session['devid'], base64_args)
Vladislav Rykov's avatar
Vladislav Rykov committed
273

Vladislav Rykov's avatar
Vladislav Rykov committed
274
275
276
            return redirect(url_for('dev', id=session['devid']))
    else:
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
277

278
279
280
281
282
283
284
285
286
287
288
289
290
@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
291

Vladislav Rykov's avatar
Vladislav Rykov committed
292

Vladislav Rykov's avatar
Vladislav Rykov committed
293
@app.route('/delete-dev')
Vladislav Rykov's avatar
Vladislav Rykov committed
294
def delete_dev():
Vladislav Rykov's avatar
Vladislav Rykov committed
295
296
    if 'name' in session and 'devid' in session:
        data.delete_table(session['appkey'], session['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
297
        res = dd.delete(session['appkey'], session['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
298

Vladislav Rykov's avatar
Vladislav Rykov committed
299
        return redirect(url_for('app_', appkey=session['appkey']))
Vladislav Rykov's avatar
Vladislav Rykov committed
300
301
    else:
        return redirect(utl_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
302
303


Vladislav Rykov's avatar
Vladislav Rykov committed
304
@app.route('/dev-data')
305
306
307
308
309
310
311
312
313
314
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
315
316
317
318
        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)
319

Vladislav Rykov's avatar
Vladislav Rykov committed
320
            if ent_cnt[1][0] > 0:
Vladislav Rykov's avatar
Vladislav Rykov committed
321
                return render_template('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
322
            else:
Vladislav Rykov's avatar
Vladislav Rykov committed
323
                return render_template('public/dev-data-t.html', devname=session['devname'])
324
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
325
            flash('Error: {}'.format(ent_cnt[1]), 'danger')
Vladislav Rykov's avatar
Vladislav Rykov committed
326
            return render_template('public/dev-data-t.html', devname=session['devname'])
327
328
329
330
    else:
        return redirect(utl_for('index'))


Vladislav Rykov's avatar
Vladislav Rykov committed
331
332
333
334
335
@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
336
            select = '<select class="form-control notifelem" id="varname" name="varname" onchange="onvar(event)" required>'
Vladislav Rykov's avatar
Vladislav Rykov committed
337
338
339
340
341
342
343
344
            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'))

345

Vladislav Rykov's avatar
Vladislav Rykov committed
346
@app.route('/data-csv')
Vladislav Rykov's avatar
Vladislav Rykov committed
347
def data_csv():
Vladislav Rykov's avatar
Vladislav Rykov committed
348
349
    if 'name' in session and 'devid' in session:
        dumpd = data.get_all(session['appkey'], session['devid'])
Vladislav Rykov's avatar
Vladislav Rykov committed
350

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

353
        with open(app.config['DATA_DOWNLOAD_DIR_OS']+'/'+fn, 'w+') as f: 
Vladislav Rykov's avatar
Vladislav Rykov committed
354
            f.write('utc,timestamp,')
Vladislav Rykov's avatar
Vladislav Rykov committed
355
356
            for d in dumpd[1][0][2]:
                f.write(d)
Vladislav Rykov's avatar
Vladislav Rykov committed
357
358
                f.write(',')
            f.write('\n')
Vladislav Rykov's avatar
Vladislav Rykov committed
359
360
        
            for row in dumpd[1]:
Vladislav Rykov's avatar
Vladislav Rykov committed
361
                f.write('{},{},'.format(row[0],row[1]))
Vladislav Rykov's avatar
Vladislav Rykov committed
362
363
364
365
                for v in row[2]:
                    f.write(str(row[2][v]))
                    f.write(',')
                f.write('\n')
Vladislav Rykov's avatar
Vladislav Rykov committed
366
    
Vladislav Rykov's avatar
Vladislav Rykov committed
367
        return send_from_directory(app.config['DATA_DOWNLOAD_DIR'], fn, as_attachment=True)
Vladislav Rykov's avatar
Vladislav Rykov committed
368
369
    else:
        return redirect(utl_for('index'))
370
371


Vladislav Rykov's avatar
Vladislav Rykov committed
372
373
374
375
376
377
378
379
380
381
382
383
384
@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
385
        users = None
Vladislav Rykov's avatar
Vladislav Rykov committed
386
        
Vladislav Rykov's avatar
Vladislav Rykov committed
387
388
        if request.method == 'POST':
            session['users_filter'] = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
389
            
Vladislav Rykov's avatar
Vladislav Rykov committed
390
391
392
393
        if 'users_filter' in session:
            users = ud.get_range_name(session['users_filter'], [MAX_PG_ENTRIES_USERS, (cur_pg-1)*MAX_PG_ENTRIES_USERS])
            print(users)
            rd = misc.paging(cur_pg, len(users[1]), MAX_PG_ENTRIES_USERS, MAX_PG)
Vladislav Rykov's avatar
Vladislav Rykov committed
394
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
395
396
397
398
            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)
        
        return render_template('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
399
400
401
    else:
        return redirect(url_for('index'))

Vladislav Rykov's avatar
Vladislav Rykov committed
402
403
404
405
406
407
408

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

409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

@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)
        # print('apps: ', apps)
        if apps[0]:
            return render_template('admin/user.html', apps=apps[1], username=name)
        else:
            return render_template('admin/user.html', feedback=apps[1], username=name)
    else:
        return render_template('public/index.html')


@app.route('/user-delete')
def user_delete():
    user = ud.get(request.args.get('name'))
Vladislav Rykov's avatar
Vladislav Rykov committed
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
    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])
                print('devs: {}'.format(devs))
                for dev in devs[1]:
                    res = data.delete_table(app[1], dev[1])
                    print ('data del {}'.format(res))
                    if not res[0]:
                        break
    
                if res[0]:
                    res = dd.delete_table(app[1])
                    print ('devices del {}'.format(res))
                    
                if res[0]:
                    res = ad.delete(app[1])
                    print ('app del {}'.format(res))

                if not res[0]:
                    break

        if res[0]:
            res = ud.delete(user[1][0])
            print ('user del {}'.format(res))

        if not res[0]:
            flash('Error: {}'.format(res[1]), 'danger')
            return render_template('admin/user.html', username=user[1][0])
        else:
                return redirect(url_for('dashboard'))
    else:
        flash('Warning: the user is admin or does not exist.' ,'warning')
        return redirect(url_for('index'))
466

Vladislav Rykov's avatar
Vladislav Rykov committed
467

468
469
470
471
@app.route('/settings', methods=['GET', 'POST'])
def settings():
    if request.method == 'GET':
        if session['role'] == 'admin':
472
            return render_template('admin/settings.html', username=session['name'], users_signup=app.config['USERS_SIGNUP'])
473
474
475
476
477
478
479
480
481
482
483
484
485
486
        else:
            return render_template('public/settings.html', username=session['name'])
    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')
487
488
489
490
491
492
                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
493
494


495
        return redirect(request.url)
496
497


498
499
@app.route('/dev-data/<var>/<dest>/<page>')
def dev_data(var, dest, page):
500
    if dest == 'graph':
501
        last = data.get_last_hours(session['appkey'], session['devid'], MAX_PG_ENTRIES_GRAPH_HOURS, int(page))
502
503
504
505
506
507
508
509
        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
510
        last = data.get_last_range(session['appkey'], session['devid'], [MAX_PG_ENTRIES_DATA, (int(page)-1)*MAX_PG_ENTRIES_DATA])
511
512
513
514
515
516
517
        #t = """ <thead>
        #            <th>Time</th>
        #            <th>{}</th>
        #        </thead>
        #        <tbody>
        #""".format(var)
        t = ''
518
519
520
        if last[0]:
            for d in last[1]:
                t += '<tr><th>'+d[1]+'</th><th>'+str(d[2][var])+'</th></tr>'
521
        #t += '</tbody>'
522
        return t
523
524


Vladislav Rykov's avatar
Vladislav Rykov committed
525
526
527
528
@app.route('/alerts')
def alerts():
    if 'name' in session:
        alerts = nfs.get_list(session['appkey'])
529
        print(alerts)
Vladislav Rykov's avatar
Vladislav Rykov committed
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
        return render_template('public/alerts.html', alert_list=alerts[1])
    else:
        return redirect(url_for('index'))

@app.route('/new-alert')
def new_alert():
    if 'name' in session:
        devs = dd.get_list(session['appkey'])
        return render_template('public/new-alert.html', devs=devs[1])
    else:
        return redirect(url_for('index'))


@app.route('/alert', methods=['POST'])
def alert():
545
546
547
548
549
    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
550
            avalue = ''
551

552
            desc = dev[1][0]+'.'+request.form['varname']+' '+request.form['operation']+' '+request.form['avalue']
553

554
            res = nfs.create(nid, session['appkey'], request.form['devid'], request.form['alertname'], desc, 'alert', request.form['alertemail'])
555
            if res[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
556
557
558
                # create new function and trigger
                tr.create_function(session['appkey'], request.form['devid'], nid, [request.form['varname'],request.form['operation'],avalue])
                tr.create(session['appkey'], request.form['devid'], nid)
559
560
561
562
563
564
565
566
567
                
                return redirect(url_for('alerts'))
            else:
                flash('Error creating new notification: {}'.format(res[1]), 'danger')
                return redirect(url_for('alerts'))
        else:
            return redirect(url_for('index'))
    else:
        return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
568
569
570
571

@app.route('/alert-rm')
def alarm_rm():
    if 'name' in session:
Vladislav Rykov's avatar
Vladislav Rykov committed
572
573
574
575
        nq.delete_list(session['appkey'])
        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('id'), request.args.get('devid'))
Vladislav Rykov's avatar
Vladislav Rykov committed
576
577

        if res[0]:
578
            flash('Alert removed', 'success')
Vladislav Rykov's avatar
Vladislav Rykov committed
579
580
            return redirect(url_for('alerts'))
        else:
581
            flash('Alert cannot be removed : {}'.format(res[1]), 'danger')
Vladislav Rykov's avatar
Vladislav Rykov committed
582
            return redirect(url_for('alerts'))
Vladislav Rykov's avatar
Vladislav Rykov committed
583
584
585
    else:
        return redirect(url_for('index'))

Vladislav Rykov's avatar
Vladislav Rykov committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
@app.route('/mail')
def send_mail():
    print (1)
    msg = Message('test message',
        sender = 'hpcaiotserver@gmail.com',
        recipients = ['al373630@uji.es'])
    print (2)
    msg.body = 'Hello vlad, alert is here!'
    print (3)
    res = mail.send(msg)
    print (res)
    return res




602
603
def pend_delete_all_ack():
    pend.delete_all_ack()
Vladislav Rykov's avatar
Vladislav Rykov committed
604