This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
2192 lines (1667 loc) · 70 KB
/
main.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
# -*- coding: utf-8 -*-
# modelr web app
# Agile Geoscience
# 2012-2014
#
from google.appengine.ext import webapp as webapp2
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import blobstore
from google.appengine.api import images
from google.appengine.api import urlfetch
from google.appengine.api import users
# For image serving
import cloudstorage as gcs
from PIL import Image, ImageFilter
import numpy as np
from jinja2 import Environment, FileSystemLoader
import time
from os.path import join, dirname
import os
import hashlib
import logging
import urllib
import urllib2
import stripe
import json
import base64
import re
import StringIO
from xml.etree import ElementTree
from default_rocks import default_rocks
from ModAuth import AuthExcept, get_cookie_string, signup, signin, \
verify, verify_signup, initialize_user, reset_password, \
forgot_password, send_message, make_user, cancel_subscription
from ModelrDb import Rock, Scenario, User, ModelrParent, Group, \
GroupRequest, ActivityLog, VerifyUser, ModelServedCount,\
ImageModel, Forward2DModel, Issue, EarthModel
# Jinja2 environment to load templates
env = Environment(loader=FileSystemLoader(join(dirname(__file__),
'templates')))
# Retry can help overcome transient urlfetch or GCS issues,
# such as timeouts.
my_default_retry_params = gcs.RetryParams(initial_delay=0.2,
max_delay=5.0,
backoff_factor=2,
max_retry_period=15)
# All requests to GCS using the GCS client within current GAE request
# and current thread will use this retry params as default. If a
# default is not set via this mechanism, the library's built-in
# default will be used. Any GCS client function can also be given a
# more specific retry params that overrides the default.
# Note: the built-in default is good enough for most cases. We
# override retry_params here only for demo purposes.
gcs.set_default_retry_params(my_default_retry_params)
#=====================================================================
# Define Global Variables
#=====================================================================
# Ancestor dB for all of modelr. Allows for strongly consistent
# database queries. (all entities update together, so every page is
# is sync)
ModelrRoot = ModelrParent.all().get()
if ModelrRoot is None:
ModelrRoot = ModelrParent()
ModelrRoot.put()
# Check if we are running the dev server
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
LOCAL = True
logging.debug("[*] Debug info activated")
stripe.verify_ssl_certs = False
else:
LOCAL = False
# Initialize the model served counter
models_served = ModelServedCount.all().ancestor(ModelrRoot).get()
if models_served is None:
models_served = ModelServedCount(count=0, parent=ModelrRoot)
models_served.put()
# Put in the default rock database under the admin account.
# The admin account is set up so every user can view our default
# scenarios and rocks
admin_id = 0
admin_user = User.all().ancestor(ModelrRoot).filter("user_id =",
admin_id).get()
# Create the admin account
if admin_user is None:
password = "Mod3lrAdm1n"
email="admin@modelr.io"
admin_user = make_user(user_id=admin_id, email=email,
password=password,
parent=ModelrRoot)
# Create the public group. All users are automatically entitled
# to part of this group.
public = Group.all().ancestor(ModelrRoot).filter("name =", 'public')
public = public.fetch(1)
if not public:
public = Group(name='public', admin=admin_user.user_id,
parent=ModelrRoot)
public.put()
# Populate the default rock database.
for i in default_rocks:
rocks = Rock.all()
rocks.filter("user =", admin_id)
rocks.filter("name =",i['name'] )
rocks = rocks.fetch(1)
if rocks:
rock = rocks[0]
else:
rock = Rock()
rock.user = admin_id
rock.name = i['name']
rock.group = 'public'
rock.description = i['description']
rock.vp = float(i['vp'])
rock.vs = float(i['vs'])
rock.rho = float(i['rho'])
rock.vp_std = float(i['vp_std'])
rock.vs_std = float(i['vs_std'])
rock.rho_std = float(i['rho_std'])
rock.put()
#====================================================================
# Global Variables
#====================================================================
# Secret API key from Stripe dashboard
PRICE = 900
tax_dict = {"AB":0.05,
"BC":0.05,
"MB":0.05,
"NB":0.13,
"NL":0.13,
"NT":0.05,
"NS":0.15,
"NU":0.05,
"ON":0.13,
"PE":0.14,
"QC":0.05,
"SK":0.05,
"YT":0.05}
UR_STATUS_DICT = {'0': 'paused',
'1': 'not checked yet',
'2': 'up',
'8': 'seems down',
'9': 'down'
}
# Helper function
def RGBToString(rgb_tuple):
"""
Convert a color to a css readable string
"""
color = 'rgb(%s,%s,%s)'% rgb_tuple
return color
class ModelrPageRequest(webapp2.RequestHandler):
"""
Base class for modelr app pages. Allows commonly used functions
to be inherited to other pages.
"""
# For the plot server
# Ideally this should be settable by an admin_user console.
if LOCAL is True:
HOSTNAME = "http://127.0.0.1:8081"
else:
HOSTNAME = "https://www.modelr.org"
def get_base_params(self, **kwargs):
'''
get the default parameters used in base_template.html
'''
user=self.verify()
if user:
email_hash = hashlib.md5(user.email).hexdigest()
else:
email_hash=''
default_rock = dict(vp=0,vs=0, rho=0, vp_std=0,
rho_std=0, vs_std=0,
description='description',
name='name', group='public')
params = dict(logout=users.create_logout_url(self.request.uri),
HOSTNAME=self.HOSTNAME,
current_rock = default_rock,
email_hash=email_hash)
params.update(kwargs)
return params
def verify(self):
"""
Verify that the current user is a legimate user. Returns the
user object from the database if true, otherwise returns None.
"""
cookie = self.request.cookies.get('user')
if cookie is None:
return
try:
user, password = cookie.split('|')
except ValueError:
return
return verify(user, password, ModelrRoot)
class MainHandler(ModelrPageRequest):
'''
main page
'''
def get(self):
# Redirect to the dashboard if the user is logged in
user = self.verify()
if user:
self.redirect('/dashboard')
template_params = self.get_base_params()
template = env.get_template('index.html')
html = template.render(template_params)
self.response.out.write(html)
class RemoveScenarioHandler(ModelrPageRequest):
'''
remove a scenario from a users db
'''
def post(self):
user = self.verify()
if user is None:
self.redirect('/signup')
return
name = self.request.get('name')
scenarios = Scenario.all()
scenarios.ancestor(user)
scenarios.filter("user =", user.user_id)
scenarios.filter("name =", name)
scenarios = scenarios.fetch(100)
for scenario in scenarios:
scenario.delete()
activity = "removed_scenario"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.redirect('/dashboard#scenarios')
class ModifyScenarioHandler(ModelrPageRequest):
'''
fetch or update a scenario.
'''
def get(self):
# Get the user but don't redirect. Guests can play with
# scenarios as well, they just can't post.
user = self.verify()
self.response.headers['Content-Type'] = 'application/json'
name = self.request.get('name')
if user:
scenarios = Scenario.all()
scenarios.ancestor(user)
scenarios.filter("user =", user.user_id)
scenarios.filter("name =", name)
scenarios = scenarios.fetch(1)
else:
scenarios=[]
# Get Evan's default scenarios (created with the admin)
scen = Scenario.all().ancestor(ModelrRoot).filter("user_id =",
admin_id)
scen = Scenario.all().filter("name =",name).fetch(100)
if scen:
scenarios += scen
if scenarios:
logging.info(scenarios[0])
logging.info(scenarios[0].data)
scenario = scenarios[0]
self.response.out.write(scenario.data)
else:
self.response.out.write('null')
activity = "fetched_scenario"
if user:
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
return
def post(self):
user = self.verify()
if user is None:
self.redirect('/signup')
return
# Output for successful post reception
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('All OK!!')
name = self.request.get('name')
group = self.request.get('group')
logging.info(('name', name))
data = self.request.get('json')
logging.info(data)
scenarios = Scenario.all()
scenarios.ancestor(user)
scenarios.filter("user =", user.user_id)
scenarios.filter("name =", name)
scenarios = scenarios.fetch(1)
# Rewrite if the name exists, create new one if it doesn't
if scenarios:
scenario = scenarios[0]
else:
scenario = Scenario(parent=user)
scenario.user = user.user_id
scenario.name = name
scenario.group = group
# Save in Db
scenario.data = data.encode()
scenario.put()
activity = "modified_scenario"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
class AddRockHandler(ModelrPageRequest):
'''
add a rock
'''
pass
class RemoveRockHandler(ModelrPageRequest):
def post(self):
user = self.verify()
if user is None:
self.redirect('/signup')
return
selected_rock = Rock.all()
selected_rock.ancestor(user)
selected_rock.filter("user =", user.user_id)
selected_rock.filter("name =", self.request.get('name'))
activity = "removed_rock"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
# Delete the rock if it exists
try:
rock = selected_rock.fetch(1)[0]
rock.delete()
except IndexError:
self.redirect('/dashboard#rocks')
else:
self.redirect('/dashboard#rocks')
class ModifyRockHandler(ModelrPageRequest):
'''
modify a rock it by name.
'''
def post(self):
user = self.verify()
if user is None:
self.redirect('/signup')
return
selected_rock = Rock.all()
selected_rock.ancestor(user)
selected_rock.filter("name =", self.request.get('name'))
current_rock = selected_rock.fetch(1)
activity = "modified_rock"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
# reload the dashboard with the rock selected for editing
try:
rock = current_rock[0]
key = rock.key()
self.redirect('/dashboard?selected_rock=' +
str(key.id()) + '#rocks')
except IndexError:
self.redirect('/dashboard#rocks')
class ScenarioHandler(ModelrPageRequest):
'''
Display the scenario page (uses scenario.html template)
'''
def get(self):
# Check for a user, but allow guests as well
user = self.verify()
self.response.headers['Content-Type'] = 'text/html'
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers['Access-Control-Allow-Headers'] = \
'X-Request, X-Requested-With'
# Get the default rocks
default_rocks = Rock.all()
default_rocks.filter("user =", admin_id)
default_rocks = default_rocks.fetch(100)
# Get the user rocks
if user:
rocks = Rock.all().ancestor(user).fetch(100)
# Get the group rocks
group_rocks = []
for group in user.group:
g_rocks = \
Rock.all().ancestor(ModelrRoot).filter("group =",
group)
group_rocks.append({"name": group.capitalize(),
"rocks": g_rocks.fetch(100)})
# Get the users scenarios
scenarios = \
Scenario.all().ancestor(user).filter("user =",
user.user_id).fetch(100)
else:
rocks = []
group_rocks = []
scenarios = []
# Get Evan's default scenarios (user id from modelr database)
scen = Scenario.all().ancestor(ModelrRoot)
scen = scen.filter("user =", admin_id).fetch(100)
if scen:
scenarios += scen
if user:
model_data = EarthModel.all().filter("user =",
user.user_id).fetch(1000)
earth_models = [{"image_key": str(i.parent_key()),
"name": i.name} for i in model_data]
else:
earth_models = []
template_params = \
self.get_base_params(user=user,rocks=rocks,
default_rocks=default_rocks,
group_rocks=group_rocks,
scenarios=scenarios,
earth_models=earth_models)
template = env.get_template('scenario.html')
html = template.render(template_params)
if user:
activity = "viewed_scenario"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.response.out.write(html)
class DashboardHandler(ModelrPageRequest):
'''
Display the dashboard page (uses dashboard.html template)
'''
def get(self):
user = self.verify()
if user is None:
self.redirect('/signin')
return
template_params = self.get_base_params(user=user)
self.response.headers['Content-Type'] = 'text/html'
# Get all the rocks
rocks = Rock.all()
rocks.ancestor(user)
rocks.filter("user =", user.user_id)
rocks.order("-date")
default_rocks = Rock.all()
default_rocks.filter("user =", admin_id)
rock_groups = []
for name in user.group:
dic = {'name': name.capitalize(),
'rocks':
Rock.all().ancestor(ModelrRoot).filter("group =",
name).fetch(100)}
rock_groups.append(dic)
# Get all the user scenarios
scenarios = Scenario.all()
if not user.user_id == admin_id:
scenarios.ancestor(user)
else:
scenarios.ancestor(ModelrRoot)
scenarios.filter("user =", user.user_id)
scenarios.order("-date")
for s in scenarios.fetch(100):
logging.info((s.name, s))
default_image_models = \
ImageModel.all().filter("user =", admin_id).fetch(100)
user_image_models = \
ImageModel.all().filter("user =", user.user_id).fetch(100)
default_models = [{"image": images.get_serving_url(i.image,
size=200,
crop=False,
secure_url=True),
"image_key": str(i.key()),
"editable": False,
"models": EarthModel.all().ancestor(i).filter("user =", user.user_id).fetch(100)}
for i in default_image_models]
user_models = [{"image": images.get_serving_url(i.image,
size=200,
crop=False,
secure_url=True),
"image_key": str(i.key()),
"editable": True,
"models": EarthModel.all().ancestor(i).filter("user =", user.user_id).fetch(100)}
for i in user_image_models]
models = user_models + default_models
template_params.update(rocks=rocks.fetch(100),
scenarios=scenarios.fetch(100),
default_rocks=default_rocks.fetch(100),
rock_groups=rock_groups,
models=models)
# Check if a rock is being edited
if self.request.get("selected_rock"):
rock_id = self.request.get("selected_rock")
current_rock = Rock.get_by_id(int(rock_id),
parent=user)
template_params['current_rock'] = current_rock
template = env.get_template('dashboard.html')
html = template.render(template_params)
activity = "dashboard"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.response.out.write(html)
def post(self):
user = self.verify()
if user is None:
self.redirect('/signup')
name = self.request.get('name')
rocks = Rock.all()
rocks.ancestor(user)
rocks.filter("user =", user.user_id)
rocks.filter("name =", name)
rocks = rocks.fetch(1)
# Rewrite if the rock exists
if rocks:
rock = rocks[0]
else:
rock = Rock(parent=user)
rock.user = user.user_id
# Populate the object
rock.vp = float(self.request.get('vp'))
rock.vs = float(self.request.get('vs'))
rock.rho = float(self.request.get('rho'))
rock.vp_std = float(self.request.get('vp_std'))
rock.vs_std = float(self.request.get('vs_std'))
rock.rho_std = float(self.request.get('rho_std'))
rock.description = self.request.get('description')
rock.name = self.request.get('name')
rock.group = self.request.get('group')
# Save in the database
rock.put()
activity = "added_rock"
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.redirect('/dashboard#rocks')
class AboutHandler(ModelrPageRequest):
def get(self):
# Uptime robot API key for modelr.io
#ur_api_key_modelr_io = 'm775980219-706fc15f12e5b88e4e886992'
# Uptime Robot API key for modelr.org REL
#ur_api_key_modelr_org = 'm775980224-e2303a724f89ef0ab886558a'
# Uptime Robot API key for modelr.org DEV
#ur_api_key_modelr_org = 'm776083114-e34c154f2239e7c273a04dd4'
ur_api_key = 'u108622-bd0a3d1e36a1bf3698514173'
# Uptime Robot IDs
ur_modelr_io = '775980219'
ur_modelr_org = '775980224' # REL, usually
# Uptime Robot URL
ur_url = 'http://api.uptimerobot.com/getMonitors'
params = {'apiKey': ur_api_key,
'monitors': ur_modelr_io + '-' + ur_modelr_org,
'customuptimeratio': '30',
'format': 'json',
'nojsoncallback':'1',
'responseTimes':'1'
}
# A dict is easily converted to an HTTP-safe query string.
ur_query = urllib.urlencode(params)
# Opened URLs are file-like.
full_url = '{0}?{1}'.format(ur_url, ur_query)
f = urllib2.urlopen(full_url)
raw_json = f.read()
user = self.verify()
models_served = ModelServedCount.all().get()
try:
j = json.loads(raw_json)
ur_ratio = j['monitors']['monitor'][0]['customuptimeratio']
ur_server_ratio = j['monitors']['monitor'][1]['customuptimeratio']
ur_server_status_code = j['monitors']['monitor'][1]['status']
ur_last_response_time = j['monitors']['monitor'][0]['responsetime'][-1]['value']
ur_last_server_response_time = j['monitors']['monitor'][1]['responsetime'][-1]['value']
ur_server_status = UR_STATUS_DICT[ur_server_status_code].upper()
template_params = \
self.get_base_params(user=user,
ur_ratio=ur_ratio,
ur_response_time=ur_last_response_time,
ur_server_ratio=ur_server_ratio,
ur_server_status=ur_server_status,
ur_server_response_time=ur_last_server_response_time,
models_served=models_served.count
)
except:
template_params = \
self.get_base_params(user=user,
ur_ratio=None,
ur_response_time=None,
ur_server_ratio=None,
ur_server_status="Unknown",
ur_server_response_time=None,
models_served=models_served.count
)
template = env.get_template('about.html')
html = template.render(template_params)
self.response.out.write(html)
class FeaturesHandler(ModelrPageRequest):
def get(self):
user = self.verify()
template_params = self.get_base_params(user=user)
template = env.get_template('features.html')
html = template.render(template_params)
self.response.out.write(html)
class FeedbackHandler(ModelrPageRequest):
def get(self):
user = self.verify()
template_params = self.get_base_params(user=user)
# Get the list of issues from GitHub.
# First, set up the request.
gh_api_key = 'token 89c9d30cddd95358b1465d1dacb1b64597b42f89'
url = 'https://api.github.com/repos/kwinkunks/modelr_app/issues'
params = {'labels':'wishlist', 'state':'open'}
query = urllib.urlencode(params)
full_url = '{0}?{1}'.format(url, query)
# Now make the request.
req = urllib2.Request(full_url)
req.add_header('Authorization', gh_api_key)
try:
resp = urllib2.urlopen(req)
raw_json = resp.read()
git_data = json.loads(raw_json)
except:
err_msg = 'Failed to retrieve issues from GitHub. Please check back later.'
git_data = {}
else:
err_msg = ''
for issue in git_data:
# Get the user's opinion.
status = None
if user:
user_issues = Issue.all().ancestor(user)
user_issue = user_issues.filter("issue_id =",
issue["id"]).get()
if user_issue:
status = user_issue.vote
else:
Issue(parent=user, issue_id=issue["id"]).put()
up, down = 0, 0
if status == 1:
up = 'true'
if status == -1:
down = 'true'
issue.update(status=status,
up=up,
down=down)
# Get the count. We have to read the database twice.
down_votes = Issue.all().ancestor(ModelrRoot).filter("issue_id =", issue["id"]).filter("vote =", -1).count()
up_votes = Issue.all().ancestor(ModelrRoot).filter("issue_id =", issue["id"]).filter("vote =", 1).count()
count = up_votes - down_votes
issue.update(up_votes=up_votes,
down_votes=down_votes,
count=count)
# Write out the results.
template_params.update(issues=git_data,
error=err_msg
)
template = env.get_template('feedback.html')
html = template.render(template_params)
self.response.out.write(html)
def post(self):
# This should never happen, because voting
# links are disabled for non-logged-in users.
user = self.verify()
if not user:
print 'no user'
return
# Get the data from the ajax call.
issue_id = int(self.request.get('id'))
up = self.request.get('up')
down = self.request.get('down')
# Set our vote flag to record the user's opinion.
if up == 'true':
issue_status = 1
elif down == 'true':
issue_status = -1
else:
issue_status = 0
# Put it in the database.
issue = Issue.all().ancestor(user).filter("issue_id =",
issue_id).get()
issue.vote = issue_status
issue.put()
# TODO log in the activity log
class PricingHandler(ModelrPageRequest):
def get(self):
user = self.verify()
template_params = self.get_base_params(user=user)
template = env.get_template('pricing.html')
html = template.render(template_params)
activity = "pricing"
if user:
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.response.out.write(html)
class HelpHandler(ModelrPageRequest):
def get(self, subpage):
if subpage:
page = subpage
else:
page = 'help'
page+= '.html'
user = self.verify()
template_params = self.get_base_params(user=user)
template = env.get_template(page)
html = template.render(template_params)
activity = "help"
if user:
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.response.out.write(html)
def post(self):
email = self.request.get('email')
message = self.request.get('message')
user = self.verify()
try:
send_message("User message %s" % email, message)
template = env.get_template('message.html')
msg = ("Thank you for your message. " +
"We'll be in touch shortly.")
html = template.render(success=msg, user=user)
self.response.out.write(html)
except:
template = env.get_template('message.html')
msg = ('Your message was not sent. ' +
'<button class="btn btn-default" '+
'onclick="goBack()">Go back and retry</button>')
html = template.render(warning=msg, user=user)
self.response.out.write(html)
class TermsHandler(ModelrPageRequest):
def get(self):
user = self.verify()
template_params = self.get_base_params(user=user)
template = env.get_template('terms.html')
html = template.render(template_params)
activity = "terms"
if user:
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.response.out.write(html)
class PrivacyHandler(ModelrPageRequest):
def get(self):
user = self.verify()
template_params = self.get_base_params(user=user)
template = env.get_template('privacy.html')
html = template.render(template_params)
activity = "privacy"
if user:
ActivityLog(user_id=user.user_id,
activity=activity,
parent=ModelrRoot).put()
self.response.out.write(html)
class ProfileHandler(ModelrPageRequest):
def get(self):
# Check for user cookies
user = self.verify()
if user is None:
self.redirect('/signup')
return
print user.unsubscribed
groups=[]
for group in user.group:
g = Group.all().ancestor(ModelrRoot).filter("name =",
group)
g = g.fetch(1)
if g:
groups.append(g[0])
template_params = self.get_base_params(user=user,
groups=groups)
if self.request.get("createfailed"):
create_error = "Group name exists"
template_params.update(create_error=create_error)
if self.request.get("joinfailed"):
join_error = "Group does not exists"
template_params.update(join_error=join_error)
# Get the user permission requests
req = \
GroupRequest.all().ancestor(ModelrRoot).filter("user =",
user.user_id)
if req:
template_params.update(requests=req)
# Get the users adminstrative requests
admin_groups = \
Group.all().ancestor(ModelrRoot).filter("admin =",
user.user_id)
admin_groups = admin_groups.fetch(100)
req = []
for group in admin_groups:
# Check for a request