-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstats.py
executable file
·1513 lines (1180 loc) · 43.9 KB
/
stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Stats Module. Run this via fcgi.
The Stats module glues all the components together into a function website.
In short, every URL is defined by some *rule* and each rule has its own method.
Then, based on the URL; a template is loaded and required variables are
loaded.
"""
# HAX.
import os
os.environ['MPLCONFIGDIR'] = '/tmp'
from jinja2 import Environment, PackageLoader
from sql import User, Script, Variable, Commit, CommitVar, \
UserScriptCache, UserScriptVariableCache, Base, Session
from webtool import WebTool, read_post_data
# Import UserTool
from query import UserTool, ScriptTool, CommitTool, VariableTool
from graph import GraphTool
# For date & time utils
import datetime
import time
# For unquote
import urllib
# For regex
import re
# For password hashes
import hashlib
from beaker.middleware import SessionMiddleware
# JSON for /api/
import simplejson as json
# Import config
from config import BASE_URL, RESULTS_PER_PAGE, \
USE_OWN_HTTPD, session_options
# XXX: Perhaps move this to query. (Also move all commit extraction to query)
from sqlalchemy import func
from sqlalchemy import extract
import sqlalchemy
import traceback, sys
# For background cache updating.
from multiprocessing import Process, Queue
# Log levels
LVL_ALWAYS = 0 # Will always be shown.
LVL_NOTABLE = 42 # Notable information.
LVL_INFORMATIVE = 314 # Informative
LVL_VERBOSE = 666 # Verbose information. This should be everything except
# stuff like what variables contain.
# We use this to check input for sanity.
alphanumspace = re.compile('^[0-9,A-z, ]+$')
emailre = re.compile('^[A-z,0-9,\._-]+@[A-z0-9.-]+\.[A-z]{2,6}$')
def get_pageid(pageid):
"""
Parses *pageid*; if it is a valid integer; the integer is returned. If
the integer is < 1; 1 is returned. If it is not an integer; 1 is
returned as well.
"""
try:
return max(int(pageid), 1)
except (ValueError, TypeError):
return 1
def template_render(template, vars, default_page=True):
"""
Template Render is a helper that initialisaes basic template variables
and handles unicode encoding.
"""
vars['_import'] = {'datetime' : datetime}
vars['baseurl'] = BASE_URL
#vars['uniencode'] = type
#vars['uniencode'] = lambda x: x.encode('utf8')
if default_page:
vars['topusers'] = ut.top(_limit=5, cache=True)
vars['topscripts'] = st.top(_limit=5, cache=True)
vars['lastcommits'] = ct.top(_limit=5)
vars['topvars'] = vt.top(_limit=5, only_vars=True, cache=True)
return unicode(template.render(vars)).encode('utf8')
# URLs:
"""
/user/:id | User Info (Total Commits, etc) Owned Scripts
/user/:id/commits | User Commits
/user/all/(:pageid) | All users. (With possible pid)
/user/id:/script/:id| User data to specific script.
/user/id:/script/:id/commits/(:pageid)
| User commits to specific script.
/script/:id | Script Info (Total Vars/Commits)
/script/:id/commits | Commits made to script. (list last X)
/script/:id/users | Users who committed to script. w/ total time
/script/all/(:pid) | All users. (With possible pid)
/commit/:id | Commit Info (Vars, time, user, script)
/commit/all | Commit List.
/variable/id: | Variable Info.
/login | Login form (GET) and login API (POST)
/logout | Delete session
/api/commit
POST Data:
User / Pass
Script
Minutes
Extra vars
/manage/scripts/ | List scripts, link to /manage/script/scriptid
| Allow script creation
/manage/script/:scriptid | Show script vars. Allow people to add vars to
| their script. (But not create not vars, nor
| delete vars from their script)
/manage/variables | Add variables to the system.
/api/script/:id | Get script info in JSON
/api/user/:id | Get user info in JSON
/api/commit/last | Get last commit info in JSON
/graph/commit/
/graph/commit/month/:id
/graph/script/:id/month:id
/graph/script/:id/user/:id/month:id
/graph/user/:id/month:id
TODO
/user/:id/scripts | All scripts user committed to
/manage/commits/ | For admins? Delete commits?
/manage/users/ | For admins?
/manage/user | ?
"""
def stats(env, start_response):
"""
Main function. Handles all the requests.
"""
log.log([], LVL_VERBOSE, PyLogger.INFO, 'Request for %s by %s' % \
(env['PATH_INFO'], env['REMOTE_ADDR']))
# Search in the known ``rules'' (see rules.py) and call function if
# existant.
r = wt.apply_rule(env['PATH_INFO'], env)
# Result 'None' means 404.
if r is None:
start_response('404 Not Found', [('Content-Type', 'text/html')])
tmpl = jinjaenv.get_template('404.html')
return template_render(tmpl, {
'url' : env['PATH_INFO'], 'session' : env['beaker.session']},
default_page=False)
# XXX: Remove statement in favour of the next
elif type(r) in (tuple, list) and len(r) >= 1 and r[0] == 'graph':
start_response('200 OK', [('Content-Type', 'image/png')])
#start_response('200 OK', [('Content-Type', 'image/svg+xml')])
r = r[1]
elif type(r) in (tuple, list) and len(r) >= 1:
# response with custom type.
start_response('200 OK', [('Content-Type', r[0])])
r = r[1]
else:
# Normal response.
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8')])
return [r]
class SessionHackException(Exception):
"""
Raised when something goes wrong.
"""
class SessionHack(object):
"""
The SessionHack middleware is used to catch any exceptions that occur;
this makes debugging easier. Typically debugging can be painful because
the trace and error is only shown in the web page.
"""
def __init__(self, app):
self.app = app
def __call__(self, env, start_response):
try:
ret = self.app(env, start_response)
except Exception, e:
print 'Exception in SessionHack:', e.message
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
raise SessionHackException(e.message)
finally:
Session.rollback()
return ret
class ScheduledJob(object):
"""
Middleware for Scheduled Jobs. Rank updates, cache updates.
"""
def __init__(self, app):
self.app = app
def __call__(self, env, start_response):
global last_rank_time
global last_rank_process
global last_rank_queue
if last_rank_process:
if last_rank_process.exitcode is not None:
last_rank_process.join()
last_rank_process = None
last_rank_queue = None
print 'Stopped running'
else:
print 'Still running'
else:
if time.time() - last_rank_time > 3600: # One hour
last_rank_time = time.time()
last_rank_queue = Queue()
last_rank_process = Process(target=update_user_ranking, args=(last_rank_queue,))
last_rank_process.start()
print 'Started a new process'
print 'Returning now'
return self.app(env, start_response)
def robots(env):
return 'User-agent: *\nDisallow: /'
def loggedin(env):
"""
Return true when logged in.
"""
if 'loggedin' in env['beaker.session']:
return env['beaker.session']['loggedin'] is True
return False
def general(env):
"""
Default page.
"""
if loggedin(env):
tmpl = jinjaenv.get_template('meinpage.html')
userid = env['beaker.session']['loggedin_id']
userinfo = ut.info(userid)
user_commits = Session.query(Commit).filter(Commit.user_id == userid
). order_by(sqlalchemy.desc(Commit.id)).limit(5).all()
script_commits = Session.query(Commit).join(
(Script, Script.id == Commit.script_id)).filter(
Script.owner_id == userid).order_by(
sqlalchemy.desc(Commit.id)).limit(5).all()
return template_render(tmpl,
{'session' : env['beaker.session'],
'user' : userinfo['user'],
'ttc' : userinfo['time']['commit_time'],
'tc' : userinfo['time']['commit_amount'],
'own_commits' : user_commits,
'script_commits' : script_commits
})
else:
tmpl = jinjaenv.get_template('base.html')
return template_render(tmpl, {'session' : env['beaker.session']} )
def user(env, userid=None):
"""
User information page. See ``user.html'' for the template.
"""
tmpl = jinjaenv.get_template('user.html')
# Also list variables for user.
uinfo = ut.info(userid, cache=True)
if uinfo is None:
return None
return template_render(tmpl,
{ 'ttc' : uinfo['time']['commit_time'],
'tc' : uinfo['time']['commit_amount'],
'vars' : uinfo['vars'],
'user' : uinfo['user'], 'session' : env['beaker.session'] }
)
def user_commit(env, userid=None, pageid=None):
"""
Page with user commits. See ``usercommits.html'' for the template.
"""
pageid = get_pageid(pageid)
tmpl = jinjaenv.get_template('usercommits.html')
session = Session()
user = Session.query(User).filter(User.id==userid).first()
user_commits = ut.listc(user, (pageid-1)*RESULTS_PER_PAGE,
RESULTS_PER_PAGE)
return template_render(tmpl,
{ 'user' : user, 'commits' : user_commits,
'pageid' : pageid,
'session' : env['beaker.session']}
)
def script(env, scriptid=None):
"""
Script information page. See ``script.html'' for the template.
"""
tmpl = jinjaenv.get_template('script.html')
sinfo = st.info(scriptid, cache=True)
if sinfo is None:
return None
return template_render(tmpl,
{ 'ttc' : sinfo['time']['commit_time'],
'tc' : sinfo['time']['commit_amount'],
'script' : sinfo['script'], 'vars' : sinfo['vars'],
'session' : env['beaker.session']
}
)
def script_commit(env, scriptid=None,pageid=None):
"""
Page with commits to script. See ``scriptcommits.html'' for the
template.
"""
pageid = get_pageid(pageid)
tmpl = jinjaenv.get_template('scriptcommits.html')
script = Session.query(Script).filter(Script.id==scriptid).first()
return template_render(tmpl,
{ 'script' : script, 'commits' : st.listc(script,
(pageid-1)*RESULTS_PER_PAGE, RESULTS_PER_PAGE),
'pageid' : pageid,
'session' : env['beaker.session']}
)
def script_graph(env, scriptid=None):
"""
Experimental function to generate graphs.
Rather messy at the moment.
"""
return None
# sinfo = st.info(scriptid)
# if sinfo is None:
# return None
##
# vars = [(x[0], x[1].name) for x in sinfo['vars']]
# script = sinfo['script']
## from sqlalchemy import func
## vars = session.query(Script.name, User.name,
## func.sum(Commit.timeadd)).join((Commit, Commit.script_id ==
## Script.id)).join((User, User.id ==
## Commit.user_id)).filter(Script.id==1).group_by(Script.name,
## User.name).all()
##
#
# fracs = []
# labels = []
#
# for x in vars:
# fracs.append(x[0])
# #fracs.append(x[2])
# labels.append(x[1])
#
# s = gt.pie(fracs,labels,'Variables for %s' % script.name)
return ['graph', s]
def commit(env, commitid=None):
"""
Page for commit-specific information. See ``commit.html'' for the
template.
"""
tmpl = jinjaenv.get_template('commit.html')
_commit = ct.info(commitid)
if _commit is None:
return None
return template_render(tmpl,
{ 'commit' : _commit, 'session' : env['beaker.session']}
)
def variable(env, variableid=None):
"""
Page for information about a variable. See ``variable.html'' for the
template.
"""
tmpl = jinjaenv.get_template('variable.html')
_variable = vt.info(variableid, cache=True)
if _variable is None:
return None
# This should really be handled by jinja
if _variable['amount'] is None:
_variable['amount'] = (0,)
return template_render(tmpl,
{ 'variable' : _variable['variable'], 'amount' :
_variable['amount'][0],
'session' : env['beaker.session'] }
)
def users(env, pageid=None):
"""
Page with a list of users.
"""
pageid = get_pageid(pageid)
tmpl = jinjaenv.get_template('users.html')
top_users = ut.top((pageid-1)*RESULTS_PER_PAGE, RESULTS_PER_PAGE, cache=True)
return template_render(tmpl,
{ 'users' : top_users,
'pageid' : pageid, 'session' : env['beaker.session']}
)
def scripts(env, pageid=None):
"""
Page with a list of scripts.
"""
pageid = get_pageid(pageid)
tmpl = jinjaenv.get_template('scripts.html')
top_scripts = st.top((pageid-1)*RESULTS_PER_PAGE, RESULTS_PER_PAGE,
cache=True)
return template_render(tmpl,
{ 'scripts' : top_scripts,
'pageid' : pageid, 'session' : env['beaker.session']}
)
def commits(env, pageid=None):
"""
Page with a list of commits.
"""
pageid = get_pageid(pageid)
tmpl = jinjaenv.get_template('commits.html')
latest_commits = ct.top((pageid-1)*RESULTS_PER_PAGE, RESULTS_PER_PAGE)
return template_render(tmpl,
{ 'commits' : latest_commits,
'pageid' : pageid, 'session' : env['beaker.session']}
)
def variables(env, pageid=None):
"""
Page with a list of variables.
"""
pageid = get_pageid(pageid)
tmpl = jinjaenv.get_template('variables.html')
top_variables = vt.top((pageid-1)*RESULTS_PER_PAGE, RESULTS_PER_PAGE,
cache=True)
return template_render(tmpl,
{ 'variables' : top_variables,
'pageid' : pageid, 'session' : env['beaker.session']}
)
# XXX: Not used
def graph_page(env):
# POST DATA CRAP XXX
tmpl = jinjaenv.get_template('graphs.html')
return template_render(tmpl, {'session': env['beaker.session']})
def user_script_stats(env, userid, scriptid):
"""
Page with information for a script specific to a user.
"""
data = ut.info_script(userid, scriptid, cache=True)
if data is None:
return None
tmpl = jinjaenv.get_template('userscript.html')
return template_render(tmpl, {
'user' : data['user'],
'script' : data['script'],
'time' : data['time'],
'vars' : data['vars'],
'session' : env['beaker.session']})
def user_script_commits(env, userid, scriptid, pageid):
"""
Page with commits made to a script by a specific user.
"""
pageid = get_pageid(pageid)
data = ut.listc_script(userid, scriptid,(pageid-1)*RESULTS_PER_PAGE,
RESULTS_PER_PAGE)
tmpl = jinjaenv.get_template('userscriptcommits.html')
return template_render(tmpl, {
'user' : data['user'],
'script' : data['script'],
'commits' : data['commits'],
'pageid' : pageid, 'session' : env['beaker.session']}
)
def login(env):
"""
Login method. Handles both GET and POST requests.
"""
tmpl = jinjaenv.get_template('loginform.html')
if str(env['REQUEST_METHOD']) == 'POST':
data = read_post_data(env)
if data is None:
return str('Error: Invalid post data')
if 'user' not in data or 'pass' not in data:
return template_render(tmpl,
{ 'session' : env['beaker.session'], 'loginfail' : True} )
data['user'] = urllib.unquote_plus(data['user'])
data['pass'] = urllib.unquote_plus(data['pass'])
data['pass'] = hashlib.sha256(data['pass']).hexdigest()
# Does the user exist (and is the password valid)?
res = Session.query(User).filter(func.lower(User.name) ==
data['user'].lower()).filter(User.password == data['pass']).first()
if res:
env['beaker.session']['loggedin'] = True
env['beaker.session']['loggedin_id'] = res.id
env['beaker.session']['loggedin_name'] = res.name
# XXX: Do not rely on this. Only use for showing permissions where
# extra checks aren't nessecary. EG: Fine for links, not fine for
# actual db changes + access to pages.
env['beaker.session']['loggedin_level'] = res.admin_level
env['beaker.session'].save()
log.log([], LVL_NOTABLE, PyLogger.INFO,
'Login %s : %s' % (env['REMOTE_ADDR'], data['user']))
return template_render(tmpl,
{ 'session' : env['beaker.session'], 'loginsuccess' : True,
'user' : res} )
else:
log.log([], LVL_NOTABLE, PyLogger.INFO,
'Failed login %s : %s' % (env['REMOTE_ADDR'], data['user']))
return template_render(tmpl,
{ 'session' : env['beaker.session'], 'loginfail' : True} )
elif str(env['REQUEST_METHOD']) == 'GET':
return template_render(tmpl,
{ 'session' : env['beaker.session']} )
else:
return None
def logout(env):
"""
Logout method.
"""
tmpl = jinjaenv.get_template('base.html')
s = env['beaker.session']
s.delete()
log.log([], LVL_NOTABLE, PyLogger.INFO,
'Logut %s' % env['REMOTE_ADDR'])
return template_render(tmpl, dict())
def api_commit(env):
"""
API to send a commit to the stats system using POST data.
"""
if str(env['REQUEST_METHOD']) != 'POST':
# 404
return None
data = read_post_data(env)
if data is None:
return None
# XXX FIXME This is ugly
pd = data.copy()
pd['password'] = 'xxxxxxxx'
log.log([], LVL_INFORMATIVE, PyLogger.INFO,
'API_COMMIT: %s, %s' % (env['REMOTE_ADDR'], pd))
if not 'user' in data or not 'password' in data:
return '110'
data['user'] = urllib.unquote_plus(data['user'])
data['password'] = urllib.unquote_plus(data['password'])
# if not alphanumspace.match(data['user']):
# return '110'
#
# if not alphanumspace.match(data['password']):
# return '110'
data['password'] = hashlib.sha256(data['password']).hexdigest()
session = Session()
user = session.query(User).filter(User.name == data['user']).filter(
User.password == data['password']).first()
if not user:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: No user' \
% (env['REMOTE_ADDR'], pd))
return '110'
del data['user']
del data['password']
if not 'script' in data:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: No script' \
% (env['REMOTE_ADDR'], pd))
return '120'
data['script'] = urllib.unquote_plus(data['script'])
script = session.query(Script).filter(Script.id == data['script']).first()
if not script:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Invalid script' \
% (env['REMOTE_ADDR'], pd))
return '120'
del data['script']
if not 'time' in data:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: No time' \
% (env['REMOTE_ADDR'], pd))
return '130'
try:
time = int(data['time'])
except ValueError:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Invalid time (int)' \
% (env['REMOTE_ADDR'], pd))
return '130'
if time < 5 or time > 60:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Invalid time (range)' \
% (env['REMOTE_ADDR'], pd))
return '130'
del data['time']
randoms = session.query(Variable).filter(Variable.is_var==0).all()
script_vars = dict(zip([x.name.lower() for x in script.variables],
script.variables))
script_vars.update(dict(zip([x.name.lower() for x in randoms], randoms)))
script_vars.update(dict(zip([x.id for x in randoms], randoms)))
script_vars.update(dict(zip([x.id for x in script.variables],
script.variables)))
vars = dict()
for x, y in data.iteritems():
x = urllib.unquote_plus(x)
x = x.lower()
try:
x = int(x)
except ValueError:
pass
if x not in script_vars:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Invalid variable for script' \
% (env['REMOTE_ADDR'], pd))
return '140'
try:
v = int(y)
except ValueError:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Invalid variable value' \
% (env['REMOTE_ADDR'], pd))
return '150'
if v < 1 or v > 10000:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Invalid variable value (%d)' \
% (env['REMOTE_ADDR'], pd, v))
return '150'
vars[script_vars[x]] = v
res = ct.add(user, script, time, vars)
if not res:
log.log([], LVL_NOTABLE, PyLogger.WARNING,
'API_COMMIT: %s, %s DENIED: Internal error' \
% (env['REMOTE_ADDR'], pd))
return '160'
return '100'
def manage_scripts(env):
"""
Page to manage scripts.
"""
if not loggedin(env):
tmpl = jinjaenv.get_template('loginform.html')
return template_render(tmpl,
{ 'session' : env['beaker.session']} )
user = Session.query(User).filter(User.id == \
env['beaker.session']['loggedin_id']).first()
if not user:
return None
tmpl = jinjaenv.get_template('managescripts.html')
return template_render(tmpl,
{ 'session' : env ['beaker.session'],
'user' : user })
def manage_script(env, scriptid):
"""
Page to manage a specific script. Handles both GET and POST.
"""
if not loggedin(env):
tmpl = jinjaenv.get_template('loginform.html')
return template_render(tmpl,
{ 'session' : env['beaker.session']} )
session = Session()
user = session.query(User).filter(User.id == \
env['beaker.session']['loggedin_id']).first()
if not user:
return None
script = session.query(Script).filter(Script.id == scriptid).first()
if not script:
return None
if script.owner.name != user.name:
return None
if str(env['REQUEST_METHOD']) == 'POST':
data = read_post_data(env)
if data is None:
return str('Error: Invalid POST data')
if 'variable' in data:
try:
id = data['variable']
except ValueError:
return str('Invalid POST data: Not a number')
var = session.query(Variable).filter(Variable.id == id).first()
if var is None:
return str('Invalid POST data: No such variable')
if var not in script.variables:
script.variables.append(var)
try:
session.commit()
except sqlalchemy.exc.IntegrityError as e:
session.rollback()
print 'Rollback in stats.py, manage_script:'
print 'Postdata:', data
print 'Exception:', e
vars = session.query(Variable).filter(Variable.is_var==1).all()
vars_intersect = filter(lambda x: x not in script.variables, vars) if \
script.variables is not None else vars
tmpl = jinjaenv.get_template('managescript.html')
return template_render(tmpl,
{ 'session' : env ['beaker.session'],
'script' : script,
'vars' : vars_intersect
})
def create_script(env):
"""
Page to create a script. Handles both GET and POST.
"""
if not loggedin(env):
tmpl = jinjaenv.get_template('loginform.html')
return template_render(tmpl,
{ 'session' : env['beaker.session']} )
session = Session()
user = session.query(User).filter(User.id == \
env['beaker.session']['loggedin_id']).first()
if not user:
return None
tmpl = jinjaenv.get_template('createscript.html')
if str(env['REQUEST_METHOD']) == 'POST':
data = read_post_data(env)
if data is None:
return str('Error: Invalid POST data')
if 'script' in data:
s = data['script']
s = urllib.unquote_plus(s)
else:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Script contains invalid characters'})
if len(s) == 0 or len(s) > 20:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Script name has invalid length'})
res = session.query(Script).filter(Script.name == s).all()
if res:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Script already exists'})
user = session.query(User).filter(User.id == \
env['beaker.session']['loggedin_id']).first()
if not user:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Invalid user in session?'})
script = Script(s)
script.owner = user
session.add(script)
try:
session.commit()
except sqlalchemy.exc.IntegrityError as e:
session.rollback()
print 'Rollback! create_script.'
print 'Post data:', data
print 'Exception:', e
return template_render(tmpl, { 'session' : env ['beaker.session'],
'newscript' : script })
return template_render(tmpl,
{ 'session' : env ['beaker.session']
})
def create_variable(env):
"""
Page to create a variable. Handles both GET and POST.
"""
if not loggedin(env):
tmpl = jinjaenv.get_template('loginform.html')
return template_render(tmpl,
{ 'session' : env['beaker.session']} )
session = Session()
user = session.query(User).filter(User.id == \
env['beaker.session']['loggedin_id']).first()
if not user:
return None
if user.admin_level < 1:
return str('Access denied')
tmpl = jinjaenv.get_template('createvariable.html')
if str(env['REQUEST_METHOD']) == 'POST':
data = read_post_data(env)
if data is None:
return str('Error: Invalid POST data')
if 'variable' in data:
s = data['variable']
s = urllib.unquote_plus(s)
else:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Variable name not specified'})
if len(s) == 0 or len(s) > 60:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Variable name has invalid length'})
# 'on' when checked; not in data when not clicked. XXX
if 'is_var' in data:
v = 1
else:
v = 0
res = session.query(Variable).filter(Variable.name ==
s).first()
if res:
return template_render(tmpl, { 'session' : env ['beaker.session'],
'error' : 'Error: Variable already exists'})
variable = Variable(s, v)
session.add(variable)
try:
session.commit()
except sqlalchemy.exc.IntegrityError as e:
session.rollback()
print 'Rollback! create_variable'
print 'Post data:', data
print 'Exception:', e
return template_render(tmpl, { 'session' : env ['beaker.session'],
'newvariable' : variable})
return template_render(tmpl,
{'session' : env['beaker.session'] })
def manage_variable(env, variableid):
"""
Page to manage a variable. Handles both GET and POST.
"""
if not loggedin(env):
tmpl = jinjaenv.get_template('loginform.html')
return template_render(tmpl,
{ 'session' : env['beaker.session']} )
session = Session()
user = session.query(User).filter(User.id == \
env['beaker.session']['loggedin_id']).first()
if not user:
return None
if user.admin_level < 1:
return str('Access denied')
tmpl = jinjaenv.get_template('managevariable.html')
variable = session.query(Variable).filter(Variable.id == \
variableid).first()
if not variable:
return None
if str(env['REQUEST_METHOD']) == 'POST':
data = read_post_data(env)
if data is None:
return str('Invalid POST data')
if 'newname' not in data:
return str('Invalid POST data')