/
api.py
1373 lines (1223 loc) · 44.5 KB
/
api.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
# Copyright (C) 2011, CloudCaptive
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
""" Author: Navraj Chohan
Description: The server side API implementation of UI.
"""
from __future__ import with_statement
import os
import wsgiref.handlers
import cgi
import locale
from serverside.entities.users import Users
from serverside.entities.accounts import Accounts
from serverside.entities.badges import Badges
from serverside.entities.badges import BadgeImage
from serverside.entities.badges import BadgeInstance
from serverside.entities.widgets import Leaderboard
from serverside.entities.widgets import Rank
from serverside.entities.widgets import Points
from serverside.entities.widgets import Notifier
from serverside.entities.widgets import TrophyCase
from serverside.entities.widgets import Milestones
from serverside.tools.utils import format_integer
from serverside.dao import badges_dao
from serverside.dao import accounts_dao
from serverside.dao import users_dao
from serverside.dao import widgets_dao
from serverside import environment
from serverside import notifier
from serverside import logs
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.api import channel
from google.appengine.api import files
from google.appengine.ext import blobstore
from serverside import constants
from django.utils import simplejson
json = simplejson
from serverside.tools.xss import XssCleaner
import hashlib
import time
import datetime
import logging
import traceback
DEBUG = constants.DEBUG
DISABLE_LOGGING = False
DISABLE_TIMING = True
"""
How keys are created for each type of entity:
User: sha1(account_id + '-' + user_id)
Badge: creatoremail + '-' badgename + '-' + badgetheme + '-' + permissions
BadgeInstance: user_id + '-' + badge_key
The dao interface should have a create key function for each
"""
def debug(msg):
if DISABLE_LOGGING:
return
if DEBUG:
frame = traceback.extract_stack(limit=1)[0]
filename, line_number, name, text = frame
logging.info('DEBUG, File "%s", line %d, in %s: %s' % (filename, line_number, name, msg))
def error(msg):
if DISABLE_LOGGING:
return
frame = traceback.extract_stack(limit=1)[0]
filename, line_number, name, text = frame
logging.error('ERROR, File "%s", line %d, in %s: %s' % (filename, line_number, name, msg))
def timing(start):
if DISABLE_TIMING:
return
end = time.time()
frame = traceback.extract_stack(limit=1)[0]
filename, line_number, name, text = frame
msg = str(start)
msg += str("," + str(end) + "," + str(end - start))
logging.info('TIMING, File "%s", line %d, in %s: %s' % (filename, line_number, name, msg))
def get_top_users(acc_ref):
if not acc_ref:
error("Unable to get users because of missing account ref")
return None
result = db.GqlQuery("SELECT * FROM Users WHERE accountRef=:1 ORDER BY points DESC LIMIT " + constants.TOP_USERS, acc_ref)
filtered = []
for index,ii in enumerate(result):
delete_index = -1
try:
if ii.profileImg == None or ii.profileImg == "":
ii.profileImg = constants.IMAGE_PARAMS.USER_AVATAR
except:
ii.profileImg = constants.IMAGE_PARAMS.USER_AVATAR
if ii.userid != constants.ANONYMOUS_USER:
if not ii.profileName:
ii.profileName = "Anonymous"
filtered.append(ii)
return filtered
def calculate_rank(user_ref, acc_ref):
rank = constants.NOT_RANKED
if not user_ref or not acc_ref:
error("Unable to cal rank because of missing user or account ref")
return rank
if user_ref.rank:
rank = user_ref.rank
last_ranking = user_ref.last_time_ranked
current_time = datetime.datetime.now()
recalculate = True
if last_ranking:
recalculate = (current_time - last_ranking) > datetime.timedelta(minutes=10)
# Do not calculate rank unless its been 10 minutes since last time
if recalculate:
result = db.GqlQuery("SELECT __key__ FROM Users WHERE accountRef=:1 ORDER BY points DESC LIMIT " + constants.NUMBER_RANKED, acc_ref)
counter = 1
is_ranked = False
for ii in result:
if ii.name() == user_ref.key().name():
is_ranked = True
break
else:
counter += 1
if is_ranked:
user_ref.rank = counter
rank = counter
else:
user_ref.rank = constants.NOT_RANKED
user_ref.last_time_ranked = current_time
user_key = user_ref.key().name()
try:
users_dao.save_user(user_ref, user_key)
except:
error("Error getting user with key %s"%user_key)
return rank
def success_ret():
ret = {'status':'success'}
ret = json.dumps(ret)
return ret
def db_error():
ret = {'status':'failed',
'errcode':constants.API_ERROR_CODES.INTERNAL_ERROR,
'error':'Database error'}
ret = json.dumps(ret)
return ret
def auth_error():
ret = {'status':'failed',
'errcode':constants.API_ERROR_CODES.NOT_AUTH,
'error':'Permission denied'}
ret = json.dumps(ret)
return ret
def bad_args():
ret = {'status':'failed',
'errcode':constants.API_ERROR_CODES.BAD_ARGS,
'error':'Number of points is not an integer'}
ret = json.dumps(ret)
return ret
def bad_user():
ret = {'status':'failed',
'errcode':constants.API_ERROR_CODES.BAD_USER,
'error':'Invalid user provided'}
ret = json.dumps(ret)
return ret
def badge_error():
ret = {'status':'failed',
'errcode':constants.API_ERROR_CODES.BADGE_NOT_FOUND,
'error':'Check your badge id'}
ret = json.dumps(ret)
return ret
def user_error():
ret = {'status':'failed',
'errcode':constants.API_ERROR_CODES.USER_NOT_FOUND,
'error':'User was not found'}
ret = json.dumps(ret)
return ret
class API_1_Status(webapp.RequestHandler):
def post(self):
start = time.time()
self.response.out.write(success_ret())
timing(start)
def get(self):
start = time.time()
self.response.out.write(success_ret())
timing(start)
class API_1_GetUserData(webapp.RequestHandler):
def post(self):
start = time.time()
api_key = self.request.get('apikey')
account_id = self.request.get('accountid')
user_id = self.request.get('userid')
user_key = users_dao.get_user_key(account_id, user_id)
acc = accounts_dao.authorize_api(account_id, api_key)
logdiction = {'event':'getuserdata',
'api': 'get_user_data',
'is_api':'yes',
'user':user_id,
'account':account_id,
'success':'true',
'ip':self.request.remote_addr}
if not acc:
logdiction['success'] = 'false'
logdiction['details'] = auth_error()
logs.create(logdiction)
self.response.out.write(auth_error())
return
user_ref = users_dao.get_user(account_id, user_id)
if not user_ref:
logdiction['success'] = 'false'
logdiction['details'] = user_error()
logs.create(logdiction)
error("User for account %s, %s not found"%(account_id, user_id))
self.response.out.write(user_error())
return
badges = badges_dao.get_user_badges(user_ref)
badge_keys = []
# get the badge image link
for b in badges:
if b.awarded == "yes":
bid = badges_dao.get_badge_id_from_instance_key(b.key().name())
badge_keys.append(bid)
ret = {"status":"success",
"user_id":user_ref.userid,
"is_enabled":user_ref.isEnabled,
"creation_date":str(user_ref.creationDate),
"points":user_ref.points,
"profile_name": user_ref.profileName,
"profile_link": user_ref.profileLink,
"profile_img": user_ref.profileImg,
"badges": badge_keys}
logs.create(logdiction)
self.response.out.write(json.dumps(ret))
timing(start)
class API_1_UpdateUser(webapp.RequestHandler):
def post(self):
start = time.time()
clean = XssCleaner()
api_key = self.request.get('apikey')
account_id = self.request.get('accountid')
new_user_id = self.request.get('userid')
# Anything that can possibly be rended should be cleaned
profile_link = self.request.get('profile_link')
if profile_link != "" and not profile_link.startswith('http://'):
profile_link = "http://" + profile_link
# We can't clean it because it will not render if embedded into a site
# Be wary of doing any queries with this data
#profile_link = clean.strip(profile_link)
profile_img = self.request.get('profile_img')
if profile_img != "" and not profile_img.startswith('http://'):
profile_img = "http://" + profile_img
#profile_img = clean.strip(profile_img)
profile_name = self.request.get('profile_name')
profile_name = clean.strip(profile_name)
logdiction = {'event':'loginuser',
'api': 'update_user',
'is_api':'yes',
'ip':self.request.remote_addr,
'user':new_user_id,
'account':account_id,
'success':'true'}
if not account_id or not new_user_id or not api_key:
self.response.out.write(bad_args())
logdiction['success'] = 'false'
logdiction['details'] = bad_args()
logs.create(logdiction)
return
acc = accounts_dao.authorize_api(account_id, api_key)
if not acc:
self.response.out.write(auth_error())
logdiction['success'] = 'false'
logdiction['details'] = auth_error()
logs.create(logdiction)
return
# Create a new user
user_key = users_dao.get_user_key(account_id, new_user_id)
#Update
user_ref = users_dao.get_user_with_key(user_key)
if user_ref:
dict = {}
update = False
if profile_link and profile_link != user_ref.profileLink:
dict["profileLink"] = profile_link
update = True
if profile_img and profile_img != user_ref.profileImg:
dict["profileImg"] = profile_img
update = True
if profile_name and profile_name != user_ref.profileName:
dict["profileName"] = profile_name
update = True
if update:
logdiction['event'] = 'updateuser'
try:
users_dao.update_user(user_key, dict, None)
except:
logdiction['success'] = 'false'
logdiction['details'] = db_error()
logs.create(logdiction)
self.response.out.write(db_error())
error("Error updating user with id %s"%new_user_id)
return
logs.create(logdiction)
self.response.out.write(success_ret())
timing(start)
return
if not profile_img:
profile_img = constants.IMAGE_PARAMS.USER_AVATAR
new_user = Users(key_name=user_key,
userid=new_user_id,
isEnabled="yes",
accountRef=acc,
profileName=profile_name,
profileLink=profile_link,
profileImg=profile_img)
logdiction['event'] = 'createuser'
try:
users_dao.save_user(new_user, user_key)
except:
logdiction['success'] = 'false'
logdiction['details'] = db_error()
logs.create(logdiction)
self.response.out.write(db_error())
error("Error getting user with key %s"%key)
return
logs.create(logdiction)
self.response.out.write(success_ret())
timing(start)
return
def get(self):
self.redirect('/html/404.html')
return
class API_1_AwardBadgePoints(webapp.RequestHandler):
def post(self):
start = time.time()
api_key = self.request.get('apikey')
account_id = self.request.get('accountid')
user_id = self.request.get('userid')
badge_ref_id = self.request.get('badgeid')
how_to_get_badge = self.request.get('how')
points = self.request.get('pointsawarded')
points_needed = self.request.get('pointsrequired')
reason = self.request.get('reason')
logdiction = {'event':'awardbadgepoints',
'api':'award_badge_points',
'user':user_id,
'is_api':'yes',
'ip':self.request.remote_addr,
'account':account_id,
'badgeid':badge_ref_id,
'points':points,
'success':'true'}
try:
points = int(points)
points_needed = int(points_needed)
except:
logdiction['success'] = 'false'
logdiction['details'] = "The number of points was not a number"
logs.create(logdiction)
self.response.out.write(bad_args())
error("Account %s -- Bad value for points awarded \
%s or points needed %s"\
%(account_id, points, points_needed ))
return
if not reason:
reason = ""
# Get the account
acc = accounts_dao.authorize_api(account_id, api_key)
if not acc:
logdiction['success'] = 'false'
logdiction['details'] = auth_error()
logs.create(logdiction)
self.response.out.write(auth_error())
return
# Get the Badge Type (used as a reference for the instances)
# Do this before getting/creating user
badge_key = badges_dao.get_key_from_badge_id(account_id, badge_ref_id)
if not badge_key:
logdiction['success'] = 'false'
logdiction['details'] = badge_error()
logs.create(logdiction)
self.response.out.write(badge_error())
error("Badge not found with key %s"%badge_ref_id)
return
# Get the user, create if it does not exist
user_ref = users_dao.get_or_create_user(account_id, user_id, acc)
if not user_ref:
logdiction['success'] = 'false'
logdiction['details'] = db_error()
logs.create(logdiction)
self.response.out.write(db_error())
return
badge_ref = badges_dao.get_badge(badge_key)
if not badge_ref:
logdiction['success'] = 'false'
logdiction['details'] = badge_error()
logs.create(logdiction)
ret = badge_error()
self.response.out.write(ret)
return
badge_instance_key = badges_dao.get_badge_instance_key(badge_key, user_id)
badge_instance_ref = badges_dao.get_badge_instance(badge_instance_key)
if not reason:
reason = badge_ref.description
link = badge_ref.downloadLink
if not badge_instance_ref:
# Create a new badge with 0 points
isawarded = "no"
if points >= points_needed:
isawarded = "yes"
perm = badges_dao.get_badge_key_permission(badge_ref_id)
new_badge_instance = badges_dao.create_badge_instance(
badge_instance_key,
badge_ref,
user_ref,
isawarded,
points,
points_needed,
perm,
link,
reason)
if isawarded == "yes":
notifier.user_badge_award(user_ref, "Badge Awarded", link, reason, acc, badge_ref_id)
logdiction['event'] = 'badgeawarded'
else:
isawarded = "no"
points_thus_far = badge_instance_ref.pointsEarned
if points:
points_thus_far += points
incr_args = {"pointsEarned":points}
reg_args = {}
# Update the following if its changed
if badge_instance_ref.pointsRequired != points_needed:
reg_args["pointsRequired"] = points_needed
if badge_instance_ref.pointsEarned < points_needed and \
points_thus_far >= points_needed:
notifier.user_badge_award(user_ref, "Badge Awarded", link, reason, acc, badge_ref_id)
logdiction['event'] = 'badgeawarded'
if points_thus_far >= points_needed:
reg_args["awarded"] = "yes"
try:
ret = badges_dao.update_badge_instance(badge_instance_key,
reg_args, incr_args)
if not ret:
raise
except:
error("Unable to update badge instance with key %s"%\
badge_instance_key)
self.response.out.write(db_error())
return
logs.create(logdiction)
ret = {"status":"success",
"badge_awarded":isawarded}
self.response.out.write(json.dumps(ret))
timing(start)
return
def get(self):
self.redirect('/html/404.html')
class API_1_AwardBadge(webapp.RequestHandler):
def post(self):
start = time.time()
api_key = self.request.get('apikey')
account_id = self.request.get('accountid')
user_id = self.request.get('userid')
badge_ref_id = self.request.get('badgeid')
reason = self.request.get('reason')
clean = XssCleaner()
reason = clean.strip(reason)
logdiction = {'event':'awardbadge',
'api':'award_badge',
'badgeid':badge_ref_id,
'is_api':'yes',
'ip':self.request.remote_addr,
'user':user_id,
'account':account_id,
'success':'true'}
# Get the account
acc = accounts_dao.authorize_api(account_id, api_key)
if not acc:
logdiction['success'] = 'false'
logdiction['details'] = auth_error()
logs.create(logdiction)
self.response.out.write(auth_error())
return
if not user_id or not badge_ref_id:
logdiction['success'] = 'false'
logdiction['details'] = bad_args()
logs.create(logdiction)
self.response.out.write(bad_args())
error("User id or badge id was not given")
return
# Make sure we have a legit badge before getting/creating a user
badge_key = badges_dao.get_key_from_badge_id(account_id, badge_ref_id)
if not badge_key:
logdiction['success'] = 'false'
logdiction['details'] = badge_error()
logs.create(logdiction)
self.response.out.write(badge_error())
return
# Get the user
user_ref = users_dao.get_or_create_user(account_id, user_id, acc)
if not user_ref:
logdiction['success'] = 'false'
logdiction['details'] = db_error()
logs.create(logdiction)
self.response.out.write(db_error())
return
badge_instance_key = badges_dao.get_badge_instance_key(badge_key, user_id)
# If the user already has it, skip the award
badge_ref = badges_dao.get_badge_instance(badge_instance_key)
if badge_ref:
if badge_ref.awarded == "yes":
logs.create(logdiction)
self.response.out.write(success_ret())
timing(start)
return
# Get the Badge Type (used as a reference for the instances)
badge_ref = badges_dao.get_badge(badge_key)
if not badge_ref:
self.response.out.write(badge_error())
return
if not reason:
reason = badge_ref.description
link = badge_ref.downloadLink
new_badge_instance = badges_dao.create_badge_instance(
badge_instance_key,
badge_ref,
user_ref,
"yes", #isawarded
0, #points
0, #points_needed
"private",
link,
reason)
name = badges_dao.get_badge_name_from_instance_key(badge_instance_key)
notifier.user_badge_award(user_ref, "Badge Awarded", link, reason, acc, badge_ref_id)
logs.create(logdiction)
self.response.out.write(success_ret())
timing(start)
return
def get(self):
self.redirect('/html/404.html')
class API_1_RemoveBadge(webapp.RequestHandler):
def post(self):
start = time.time()
api_key = self.request.get('apikey')
account_id = self.request.get('accountid')
user_id = self.request.get('userid')
badge_ref_id = self.request.get('badgeid')
logdiction = {'event':'removebadge',
'api':'remove_badge',
'badgeid':badge_ref_id,
'is_api':'yes',
'ip':self.request.remote_addr,
'user':user_id,
'account':account_id,
'success':'true'}
# Get the account
acc = accounts_dao.authorize_api(account_id, api_key)
if not acc:
logdiction['success'] = 'false'
logdiction['details'] = auth_error()
logs.create(logdiction)
self.response.out.write(auth_error())
return
if not user_id or not badge_ref_id:
logdiction['success'] = 'false'
logdiction['details'] = bad_args()
logs.create(logdiction)
self.response.out.write(bad_args())
return
badge_key = badges_dao.get_key_from_badge_id(account_id, badge_ref_id)
if not badge_key:
logdiction['success'] = 'false'
logdiction['details'] = badge_error()
logs.create(logdiction)
self.response.out.write(badge_error())
return
# Get the user
user_ref = users_dao.get_or_create_user(account_id, user_id, acc)
if not user_ref:
logdiction['success'] = 'false'
logdiction['details'] = db_error()
logs.create(logdiction)
self.response.out.write(db_error())
return
badge_instance_key = badges_dao.get_badge_instance_key(badge_key, user_id)
# Get the Badge Type (used as a reference for the instances)
badge_ref = badges_dao.get_badge(badge_key)
if not badge_ref:
logdiction['success'] = 'false'
logdiction['details'] = badge_error()
logs.create(logdiction)
self.response.out.write(badge_error())
return
try:
new_badge_instance = badges_dao.delete_badge_instance(badge_instance_key)
except:
logdiction['success'] = 'false'
logdiction['details'] = db_error()
logs.create(logdiction)
self.response.out.write(db_error())
return
logs.create(logdiction)
self.response.out.write(success_ret())
timing(start)
return
def get(self):
self.redirect('/html/404.html')
class API_1_GetWidget(webapp.RequestHandler):
def post(self):
"""This post is for priming/prefetching,
not actually delivering the widget
"""
start = time.time()
api_key = self.request.get('apikey')
account_id = self.request.get('accountid')
user_id = self.request.get('userid')
widget_type = self.request.get('widget')
logdiction = {'event':'prefetchwidget',
'api':'get_widget',
'user':user_id,
'is_api':'yes',
'ip':self.request.remote_addr,
'account':account_id,
'widget':widget_type,
'success':'true'}
if widget_type not in constants.VALID_WIDGETS:
logdiction['success'] = 'false'
logdiction['details'] = "Using an invalid widget name"
logs.create(logdiction)
self.response.out.write(bad_args())
return
# Get the account
acc_ref = accounts_dao.authorize_api(account_id, api_key)
if not acc_ref:
logdiction['success'] = 'false'
logdiction['details'] = auth_error()
logs.create(logdiction)
self.response.out.write(auth_error())
return
if not user_id and widget_type in constants.WIDGETS_THAT_DONT_NEED_A_USER:
user_id = constants.ANONYMOUS_USER
if not user_id:
logdiction['success'] = 'false'
logdiction['details'] = bad_args()
logs.create(logdiction)
self.response.out.write(bad_args())
return
user_ref = None
if user_id:
user_ref = users_dao.get_user_with_key(user_id)
if not user_ref and user_id == constants.ANONYMOUS_USER:
users_dao.create_new_user(account_id, constants.ANONYMOUS_USER)
#acc_ref = users_dao.get_account_from_user(user_ref)
# TODO Need to measure if there is an actual gain from this prefetching
# or if it's causing unnecessary contention
values = getattr(self, widget_type + "_values")(user_ref, acc_ref, 500, 300)
logs.create(logdiction)
return
def get(self):
""" Users fetch their widgets from here """
start = time.time()
user_key = self.request.get('u')
if not user_key:
self.redirect('/html/404.html')
return
height = self.request.get('height')
width = self.request.get('width')
widget_type = self.request.get('widget')
if widget_type not in constants.VALID_WIDGETS:
self.redirect('/html/404.html')
error("Fetching widget type " + str(widget_type))
return
# TODO make sure the account has permission to the type of widget
# as of right now all widgets are enabled
user_ref = users_dao.get_user_with_key(user_key)
acc_ref = users_dao.get_account_from_user(user_ref)
user_id = ""
acc_id = ""
if user_ref: user_id = user_ref.key().name()
if acc_ref: acc_id = acc_ref.key().name()
logdiction = {'event':'viewwidget',
'api':'get_widget',
'user':user_id,
'is_api':'yes',
'ip':self.request.remote_addr,
'account':acc_id,
'widget':widget_type,
'success':'true'}
values = getattr(self, widget_type + "_values")(user_ref, acc_ref, height, width)
path = os.path.join(os.path.dirname(__file__), 'widgets/v1.0/' +
widget_type + ".html")
#TODO minify temp code, lots of white space right now
temp = template.render(path, values)
logs.create(logdiction)
self.response.out.write(temp)
timing(start)
return
def trophy_case_values(self, user_ref, acc_ref, height, width):
badges = badges_dao.get_user_badges(user_ref)
tcase_ref = None
if not acc_ref:
tcase_ref = TrophyCase()
else:
try:
tcase_ref = acc_ref.trophyWidget
except:
tcase_ref = widgets_dao.add_trophy_case(acc_ref)
awarded_badges= []
for b in badges:
if b.awarded == "yes":
awarded_badges.append(b)
# here we get the custom trophy case settings
# Grab all the badge urls
ret = {"status":"success"}
for ii in tcase_ref.properties():
ret[ii] = getattr(tcase_ref, ii)
ret["badges"] = awarded_badges
# Internal div's need to be slighy smaller than the iframe
if width and height:
try:
width = int(width)
height = int(height)
# How did I get this equation? Trial and error.
height = height - 2 *int(ret['borderThickness']) - 8
width = width - 2 *int(ret['borderThickness']) - 8
ret['height'] = height
ret['width'] = width
except:
pass
return ret
def notifier_values(self, user_ref, acc_ref, height, width):
token = 0
notifier_ref = None
if not acc_ref:
notifier_ref = Notifier()
else:
try:
notifier_ref = acc_ref.notifierWidget
except:
notifier_ref = widgets_dao.add_notifier(acc_ref)
token = notifier.get_channel_token(user_ref)
ret = {"status":"success"}
ret["token"] = token
# here we get the custom settings
for ii in notifier_ref.properties():
ret[ii] = getattr(notifier_ref, ii)
# Internal div's need to be slighy smaller than the iframe
if width and height:
try:
width = int(width)
height = int(height)
# How did I get this equation? Trial and error.
height = height - 2 *int(ret['borderThickness']) - 8
width = width - 2 *int(ret['borderThickness']) - 16
#height = height - 2 *int(ret['borderThickness']) - 8
#width = width - 2 *int(ret['borderThickness']) - 8
ret['height'] = height
ret['width'] = width
except:
pass
return ret
def milestones_values(self, user_ref, acc_ref, height, width):
user_badges = badges_dao.get_user_badges(user_ref)
acc_badges = badges_dao.get_rendereable_badgeset(acc_ref)
mcase_ref = None
if not acc_ref:
mcase_ref = Milestones()
else:
try:
mcase_ref = acc_ref.milestoneWidget
except:
mcase_ref = widgets_dao.add_milestones(acc_ref)
if user_ref and user_ref.userid == constants.ANONYMOUS_USER:
user_badges = []
badge_count = 0
display_badges = []
for badge in user_badges:
b = {}
try:
# In case the badge was removed, we'll skip it
b["badgeRef"] = badge.badgeRef
except Exception, e:
continue
if badge.awarded == "yes":
b["awarded"] = True
else:
b["awarded"] = True
b["id"] = badge_count
b["awarded"] = badge.awarded
b["pointsRequired"] = badge.pointsRequired
# backward compatibility
if badge.pointsRequired == 9999999999:
b["pointsRequired"] = 0
if badge.pointsEarned > badge.pointsRequired:
b["pointsEarned"] = badge.pointsRequired
else:
b["pointsEarned"] = badge.pointsEarned
b["resource"] = badge.resource
b["reason"] = badge.reason
b["downloadLink"] = badge.downloadLink
b["id"] = badge_count
badge_count += 1
display_badges.append(b)
# Put all badges that have not been awarded
to_add = []
for aa in acc_badges:
is_there = False
for dd in display_badges:
if aa["key"] == dd["badgeRef"].key().name():
is_there = True
if not is_there:
b = {}
b["id"] = badge_count
b["awarded"] = False
b["pointsEarned"] = 0
b["pointsRequired"] = 0
# This name should not have changed
b["resource"] = ""
b["reason"] = aa["description"]
b["downloadLink"] = aa["downloadLink"]
badge_count += 1
to_add.append(b)
display_badges.extend(to_add)
ret = {"status":"success"}
for ii in mcase_ref.properties():
ret[ii] = getattr(mcase_ref, ii)
ret["badges"] = display_badges
# Internal div's need to be slighy smaller than the iframe
if width and height:
try:
width = int(width)
height = int(height)
# How did I get this equation? Trial and error.
height = height - 2 *int(ret['borderThickness']) - 8
width = width - 2 *int(ret['borderThickness']) - 8
ret['height'] = height
ret['width'] = width
except:
pass
ret['barSize'] = ret['imageSize']
return ret
def leaderboard_values(self, user_ref, acc_ref, height, width):
leader_ref = None
if not acc_ref:
leader_ref = Leaderboard()
else:
try:
leader_ref = acc_ref.leaderWidget
if leader_ref == None:
leader_ref = widgets_dao.add_leader(acc_ref)
except:
leader_ref = widgets_dao.add_leader(acc_ref)
# here we get the custom rank settings
ret = {"status":"success"}
ret['users'] = get_top_users(acc_ref)
for ii in leader_ref.properties():
ret[ii] = getattr(leader_ref, ii)
# Internal div's need to be slighy smaller than the iframe
if width and height:
try:
width = int(width)
height = int(height)
# How did I get this equation? Trial and error.
height = height - 2 *int(ret['borderThickness']) - 8
width = width - 2 *int(ret['borderThickness']) - 8
ret['height'] = height
ret['width'] = width
except:
pass
return ret
def points_values(self, user_ref, acc_ref, height, width):
points = 0
if user_ref:
points = user_ref.points
points_ref = None
if not acc_ref:
points_ref = Points()
else:
try:
points_ref = acc_ref.pointsWidget
except:
points_ref = widgets_dao.add_points(acc_ref)
ret = {"status":"success"}