-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathserver.py
1335 lines (1083 loc) · 49.7 KB
/
server.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
from bson.objectid import ObjectId
from datetime import datetime
from flask import Flask, request, Response, jsonify
from flask.ext import restful
from flask.ext.restful import reqparse
from pymongo import MongoClient
import re
import sys
import alias_service
import model as M
import rankings
from config.config import Config
from dao import Dao
from scraper.tio import TioScraper
from scraper.challonge import ChallongeScraper
from scraper.smashgg import SmashGGScraper
from scripts import create_region
from scripts import create_user
TYPEAHEAD_PLAYER_LIMIT = 20
BASE_REGION = 'newjersey'
# parse config file
config = Config()
mongo_client = MongoClient(host=config.get_mongo_url())
print "parsed config: ", config.get_mongo_url()
app = Flask(__name__)
api = restful.Api(app)
player_list_get_parser = reqparse.RequestParser()
player_list_get_parser.add_argument('alias', type=str)
player_list_get_parser.add_argument('query', type=str)
player_list_get_parser.add_argument('all', type=bool)
tournament_list_get_parser = reqparse.RequestParser()
tournament_list_get_parser.add_argument('includePending', type=str)
matches_get_parser = reqparse.RequestParser()
matches_get_parser.add_argument('opponent', type=str)
rankings_get_parser = reqparse.RequestParser()
rankings_get_parser.add_argument('generateNew', type=str)
player_put_parser = reqparse.RequestParser()
player_put_parser.add_argument('name', type=str)
player_put_parser.add_argument('aliases', type=list)
player_put_parser.add_argument('regions', type=list)
tournament_put_parser = reqparse.RequestParser()
tournament_put_parser.add_argument('name', type=str)
tournament_put_parser.add_argument('date', type=str)
tournament_put_parser.add_argument('players', type=list)
tournament_put_parser.add_argument('matches', type=list)
tournament_put_parser.add_argument('regions', type=list)
tournament_put_parser.add_argument('pending', type=bool)
smashGGMap_get_parser = reqparse.RequestParser()
smashGGMap_get_parser.add_argument('bracket_url', type=str)
rankings_criteria_get_parser = reqparse.RequestParser()
rankings_criteria_get_parser.add_argument('ranking_activity_day_limit', type=str)
rankings_criteria_get_parser.add_argument('ranking_num_tourneys_attended', type=str)
rankings_criteria_get_parser.add_argument('tournament_qualified_day_limit', type=str)
rankings_criteria_get_parser.add_argument('tournament_id_to_diff', type=str)
merges_put_parser = reqparse.RequestParser()
merges_put_parser.add_argument('source_player_id', type=str)
merges_put_parser.add_argument('target_player_id', type=str)
tournament_import_parser = reqparse.RequestParser()
tournament_import_parser.add_argument(
'tournament_name', type=str, required=True, help="Tournament must have a name.")
tournament_import_parser.add_argument(
'bracket_type', type=str, required=True, help="Bracket must have a type.")
tournament_import_parser.add_argument('challonge_url', type=str)
tournament_import_parser.add_argument('tio_file', type=str)
tournament_import_parser.add_argument('tio_bracket_name', type=str)
tournament_import_parser.add_argument('included_phases', type=list)
pending_tournament_put_parser = reqparse.RequestParser()
pending_tournament_put_parser.add_argument('name', type=str)
pending_tournament_put_parser.add_argument('players', type=list)
pending_tournament_put_parser.add_argument('matches', type=list)
pending_tournament_put_parser.add_argument('regions', type=list)
pending_tournament_put_parser.add_argument('alias_to_id_map', type=list)
tournament_details_add_match_parser = reqparse.RequestParser()
tournament_details_add_match_parser.add_argument('tournament_id', type=str)
tournament_details_add_match_parser.add_argument('winner_id', type=str)
tournament_details_add_match_parser.add_argument('loser_id', type=str)
tournament_details_exclude_match_parser = reqparse.RequestParser()
tournament_details_exclude_match_parser.add_argument('tournament_id', type=str)
tournament_details_exclude_match_parser.add_argument('match_id', type=str)
tournament_details_exclude_match_parser.add_argument('excluded_tf', type=str)
tournament_details_swap_winner_loser_parser = reqparse.RequestParser()
tournament_details_swap_winner_loser_parser.add_argument('tournament_id', type=str)
tournament_details_swap_winner_loser_parser.add_argument('match_id', type=str)
session_put_parser = reqparse.RequestParser()
session_put_parser.add_argument('username', type=str)
session_put_parser.add_argument('password', type=str)
session_delete_parser = reqparse.RequestParser()
session_delete_parser.add_argument('session_id', location='cookies', type=str)
admin_functions_parser = reqparse.RequestParser()
admin_functions_parser.add_argument('function_type', location='json', type=str)
admin_functions_parser.add_argument('new_region', location='json', type=str)
admin_functions_parser.add_argument('new_user_name', location='json', type=str)
admin_functions_parser.add_argument('new_user_pass', location='json', type=str)
admin_functions_parser.add_argument('new_user_permissions', location='json', type=str)
admin_functions_parser.add_argument('new_user_regions', location='json', type=list)
#TODO: major refactor to move auth code to a decorator
class InvalidAccessToken(Exception):
pass
def is_allowed_origin(origin):
dragon = r"http(s)?:\/\/(stage\.|www\.)?(notgarpr\.com|192\.168\.[^\.]+\.[^\.]+?|njssbm\.com|garpr\.com)(\:[\d]*)?$"
return re.match(dragon, origin)
def get_user_from_request(request, dao):
session_id = request.cookies.get('session_id')
print "session: %s" % session_id
return dao.get_user_by_session_id_or_none(session_id)
def is_user_admin_for_region(user, region):
if not region:
return False
if not user.admin_regions:
return False
if "".join(region) in user.admin_regions:
return True
return False
def is_user_admin_for_regions(user, regions):
'''
returns true is user is an admin for ANY of the regions
'''
if len(set(regions).intersection(user.admin_regions)) == 0:
return False
else:
return True
class RegionListResource(restful.Resource):
def get(self):
regions_dict = {'regions': [
r.dump(context='web') for r in Dao.get_all_regions(mongo_client)]}
return regions_dict
class PlayerListResource(restful.Resource):
def _player_matches_query(self, player, query):
player_name = player.name.lower()
query = query.lower()
# try matching the full name first
if player_name == query:
return True
# if query is >= 3 chars, allow substring matching
# this is to allow players with very short names to appear for small
# search terms
if len(query) >= 3 and query in player_name:
return True
# split the player name on common dividers and try to match against
# each part starting from the beginning
# split on: . | space
tokens = re.split('\.|\|| ', player_name)
for token in tokens:
if token:
if token.startswith(query):
return True
# no match
return False
def _get_players_matching_query(self, players, query):
matching_players = []
for player in players:
if self._player_matches_query(player, query):
matching_players.append(player)
# move exact matches to the front so that short names are guaranteed to
# appear
for i in xrange(len(matching_players)):
player = matching_players[i]
if player.name.lower() == query:
matching_players.insert(0, matching_players.pop(i))
matching_players = matching_players[:TYPEAHEAD_PLAYER_LIMIT]
return matching_players
def get(self, region):
args = player_list_get_parser.parse_args()
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
return_dict = {}
exclude_properties = ['aliases']
# single player matching alias within region
if args['alias']:
return_dict['players'] = []
db_player = dao.get_player_by_alias(args['alias'])
if db_player:
return_dict['players'].append(db_player.dump(context='web',
exclude=exclude_properties))
# search multiple players by name across all regions
elif args['query']:
# TODO: none checks on below list comprehensions
all_players = dao.get_all_players(all_regions=True)
return_dict['players'] = [p.dump(context='web',
exclude=exclude_properties)
for p in self._get_players_matching_query(all_players, args['query'])]
# get all players in all regions
elif args['all']:
all_players = dao.get_all_players(all_regions=True)
return_dict['players'] = [p.dump(context='web',
exclude=exclude_properties)
for p in sorted(all_players, key=lambda player: player.name.lower())]
# all players within region
else:
print 'test'
return_dict['players'] = [p.dump(context='web',
exclude=exclude_properties)
for p in sorted(dao.get_all_players(),
key=lambda player: player.name.lower())]
return return_dict
class PlayerResource(restful.Resource):
def get(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
player = None
try:
player = dao.get_player_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if not player:
return 'Player not found', 404
return player.dump(context='web')
def put(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
player = None
try:
player = dao.get_player_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if not player:
return "No player found with that region/id.", 404
# TODO auth for this needs to be different, otherwise an admin can tag
# with their region and then edit everything
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
# remove auth for now (for players not part of any regions)
# I think possibly we should remove admin_regions or at least
# figure out how we want them to work;
# if not is_user_admin_for_regions(user, player.regions):
# return 'Permission denied', 403
args = player_put_parser.parse_args()
if args['name']:
player.name = args['name']
if args['aliases'] is not None:
for a in args['aliases']:
if not isinstance(a, unicode):
return "each alias must be a string", 400
new_aliases = [a.lower() for a in args['aliases']]
if player.name.lower() not in new_aliases:
return "aliases must contain the players name!", 400
player.aliases = new_aliases
if args['regions'] is not None:
for a in args['regions']:
if not isinstance(a, unicode):
return "each region must be a string", 400
player.regions = args['regions']
dao.update_player(player)
return player.dump(context='web')
def delete(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
try:
player = dao.get_player_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if not player:
return "No player found with that region/id.", 404
if not is_user_admin_for_regions(user, player.regions):
return 'Permission denied', 403
if dao.get_all_tournaments(players=[player]):
return 'Player still has matches', 400
dao.delete_player(player)
return {"success": True}
class TournamentSeedResource(restful.Resource):
def post(self, region):
print "in tournamentSeed POST"
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
parser = reqparse.RequestParser()
parser.add_argument('type', type=str, location='json')
parser.add_argument('data', type=unicode, location='json')
parser.add_argument('bracket', type=str, location='json')
args = parser.parse_args()
if args['data'] is None:
return "data required", 400
the_bytes = bytearray(args['data'], "utf8")
if the_bytes[0] == 0xef:
print "found magic numbers"
return "magic numbers!", 503
type = args['type']
data = args['data']
pending_tournament = None
try:
if type == 'challonge':
scraper = ChallongeScraper(data)
else:
return "Unknown type", 400
pending_tournament, raw_file = M.PendingTournament.from_scraper(type, scraper, region)
except Exception as ex:
return 'Scraper encountered an error ' + str(ex), 400
if not pending_tournament or not raw_file:
return 'Scraper encountered an error - null', 400
pending_tournament_json = pending_tournament.dump(context='web', exclude=('date', 'matches', 'regions', 'type'))
return pending_tournament_json
class TournamentListResource(restful.Resource):
def get(self, region):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
include_pending_tournaments = False
args = tournament_list_get_parser.parse_args()
if args['includePending'] and args['includePending'] == 'true':
user = get_user_from_request(request, dao)
include_pending_tournaments = user and is_user_admin_for_region(
user, region)
tournaments = dao.get_all_tournaments(regions=[region])
only_properties = ('id',
'name',
'date',
'regions')
# temporary fix
all_tournament_jsons = []
for t in tournaments:
try:
all_tournament_jsons.append(t.dump(context='web',
only=only_properties))
except:
print 'error inserting tournament', t
if include_pending_tournaments:
# add a pending field for all existing tournaments
for t in all_tournament_jsons:
t['pending'] = False
pending_tournaments = dao.get_all_pending_tournaments(regions=[
region])
if pending_tournaments:
for p in pending_tournaments:
try:
p = p.dump(context='web',
only=only_properties)
p['pending'] = True
all_tournament_jsons.append(p)
except:
print 'error inserting pending tournament', p
return_dict = {}
return_dict['tournaments'] = all_tournament_jsons
return return_dict
def post(self, region):
print "in tournamentList POST"
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
if not is_user_admin_for_region(user, region):
return 'Permission denied', 403
parser = reqparse.RequestParser()
parser.add_argument('type', type=str, location='json')
parser.add_argument('data', type=unicode, location='json')
parser.add_argument('bracket', type=str, location='json')
parser.add_argument('included_phases', type=list, location='json')
args = parser.parse_args()
if args['data'] is None:
return "data required", 400
the_bytes = bytearray(args['data'], "utf8")
if the_bytes[0] == 0xef:
print "found magic numbers"
return "magic numbers!", 503
type = args['type']
data = args['data']
included_phases = args['included_phases']
pending_tournament = None
try:
if type == 'tio':
if args['bracket'] is None:
return "Missing bracket name", 400
data_bytes = bytes(data)
if data_bytes[0] == '\xef':
data = data[:3]
scraper = TioScraper(data, args['bracket'])
elif type == 'challonge':
scraper = ChallongeScraper(data)
elif type == 'smashgg':
scraper = SmashGGScraper(data, included_phases)
else:
return "Unknown type", 400
pending_tournament, raw_file = M.PendingTournament.from_scraper(
type, scraper, region)
except Exception as ex:
return 'Scraper encountered an error ' + str(ex), 400
if not pending_tournament or not raw_file:
return 'Scraper encountered an error', 400
try:
pending_tournament.alias_to_id_map = alias_service.get_alias_to_id_map_in_list_format(
dao, pending_tournament.players)
except:
return 'Alias service encountered an error', 400
# If the tournament is too large, don't insert the raw file into the db.
if len(pending_tournament.players) < 1000:
try:
raw_file = dao.insert_raw_file(raw_file)
except Exception as ex:
print ex
return 'Dao insert_raw_file encountered an error', 400
else:
print 'Skipping inserting raw file for tournament because it is too large'
try:
new_id = dao.insert_pending_tournament(pending_tournament)
return_dict = {
'id': str(new_id)
}
return return_dict
except Exception as ex:
print ex
return 'Dao insert_pending_tournament encountered an error', 400
return 'Unknown error!', 400
# TODO: we shouldn't be doing this, instead we should pass the relevant player/
# match information in different objects
def convert_tournament_to_response(tournament, dao):
return_dict = tournament.dump(context='web', exclude=('orig_ids',))
return_dict['players'] = [{
'id': p,
'name': dao.get_player_by_id(ObjectId(p)).name
} for p in return_dict['players']]
return_dict['matches'] = [{
'winner_id': m['winner'],
'loser_id': m['loser'],
'winner_name': dao.get_player_by_id(ObjectId(m['winner'])).name,
'loser_name': dao.get_player_by_id(ObjectId(m['loser'])).name,
'match_id': m['match_id'],
'excluded': m['excluded']
} for m in return_dict['matches']]
return return_dict
class TournamentResource(restful.Resource):
def get(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
response = None
tournament = None
try:
tournament = dao.get_tournament_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if tournament is not None:
response = convert_tournament_to_response(tournament, dao)
else:
user = get_user_from_request(request, dao)
# this usage is safe, if the ID was fake, we would have already
# blown the coop above
pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
if not pending_tournament:
return 'Not found!', 404
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, pending_tournament.regions):
return 'Permission denied', 403
response = pending_tournament.dump(context='web')
return response
def put(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
tournament = None
args = tournament_put_parser.parse_args()
try:
if args['pending']:
tournament = dao.get_pending_tournament_by_id(ObjectId(id))
else:
tournament = dao.get_tournament_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if not tournament:
return "No tournament found with that id.", 404
# TODO auth for this needs to be different, otherwise an admin can tag
# with their region and then edit everything
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, tournament.regions):
return 'Permission denied', 403
if args['name']:
tournament.name = args['name']
if args['date']:
try:
tournament.date = datetime.strptime(
args['date'].strip(), '%m/%d/%y')
except:
return "Invalid date format", 400
if args['players']:
# this should rarely be used (if it is used, players will not unmerge reliably)
for p in args['players']:
if not isinstance(p, dict):
return "each player must be a dict", 400
tournament.players = [ObjectId(p['id']) for p in args['players']]
tournament.orig_ids = [pid for pid in tournament.players]
if args['matches']:
for m in args['matches']:
if not isinstance(m, dict):
return "matches must be a dict", 400
if (not isinstance(m['winner_id'], unicode) or
not isinstance(m['winner_name'], unicode) or
not isinstance(m['loser_id'], unicode) or
not isinstance(m['loser_name'], unicode) or
not isinstance(m['excluded'], bool) or
not isinstance(m['match_id'], int)):
return "invalid arguments for match", 400
# turn the list of dicts into list of matchresults
matches = [
M.Match(
winner=ObjectId(m['winner_id']),
loser=ObjectId(m['loser_id']),
match_id=m['match_id'],
excluded=m['excluded'])
for m in args['matches']]
tournament.matches = matches
if args['regions']:
for p in args['regions']:
if not isinstance(p, unicode):
return "each region must be a string", 400
tournament.regions = args['regions']
if args['pending']:
dao.update_pending_tournament(tournament)
else:
print tournament
dao.update_tournament(tournament)
if args['pending']:
return dao.get_pending_tournament_by_id(tournament.id).dump(context='web')
else:
return convert_tournament_to_response(dao.get_tournament_by_id(tournament.id), dao)
def delete(self, region, id):
""" Deletes a tournament.
Route restricted to admins for this region.
Be VERY careful when using this """
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
tournament_to_delete = None
try:
tournament_to_delete = dao.get_pending_tournament_by_id(
ObjectId(id))
except:
return 'Invalid ObjectID', 400
if tournament_to_delete: # its a pending tournament
if not is_user_admin_for_regions(user, tournament_to_delete.regions):
return 'Permission denied', 403
dao.delete_pending_tournament(tournament_to_delete)
else: # not a pending tournament, might be a finalized tournament
tournament_to_delete = dao.get_tournament_by_id(
ObjectId(id)) # ID must be valid if we got here
if not tournament_to_delete: # can't find anything, whoops
return "No tournament (pending or finalized) found with that id.", 404
if not is_user_admin_for_regions(user, tournament_to_delete.regions):
return 'Permission denied', 403
dao.delete_tournament(tournament_to_delete)
return {"success": True}
class PendingTournamentResource(restful.Resource):
"""
Currently only updates the alias_to_id_map in the pending tournament
"""
def put(self, region, id):
print "in pending tournament put"
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
pending_tournament = None
try:
pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if not pending_tournament:
return "No pending tournament found with that id.", 404
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, pending_tournament.regions):
return 'Permission denied', 403
args = pending_tournament_put_parser.parse_args()
data = {'alias_to_id_map': [M.AliasMapping.load(
alias_item, context='web') for alias_item in args['alias_to_id_map']]}
if not data:
return 'Request couldnt be converted to pending tournament', 400
try:
print "Incoming", data["alias_to_id_map"]
print "DB", pending_tournament.alias_to_id_map
for alias_item in data["alias_to_id_map"]:
player_alias = alias_item.player_alias
player_id = alias_item.player_id
pending_tournament.set_alias_id_mapping(
player_alias, player_id)
except:
print 'Error processing alias_to_id map'
return 'Error processing alias_to_id map', 400
try:
dao.update_pending_tournament(pending_tournament)
return pending_tournament.dump(context='web')
except:
return 'Encountered an error inserting pending tournament', 400
class FinalizeTournamentResource(restful.Resource):
""" Converts a pending tournament to a tournament.
Works only if the PendingTournament's alias_to_id_map is completely filled out.
Route restricted to admins for this region. """
def post(self, region, id):
print "finalize tournament post"
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
pending_tournament = None
try:
pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400
if not pending_tournament:
return 'No pending tournament found with that id.', 400
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, pending_tournament.regions):
return 'Permission denied', 403
# Make sure multiple player aliases don't map to a single player ID.
player_ids = set()
for mapping in pending_tournament.alias_to_id_map:
if mapping.player_id is not None:
if mapping.player_id in player_ids:
return "Player id %s is already mapped" % mapping.player_id, 400
else:
player_ids.add(mapping.player_id)
new_player_names = []
for mapping in pending_tournament.alias_to_id_map:
if mapping.player_id is None:
new_player_names.append(mapping.player_alias)
for player_name in new_player_names:
player = M.Player.create_with_default_values(player_name, region)
player_id = dao.insert_player(player)
pending_tournament.set_alias_id_mapping(player_name, player_id)
# validate players in this tournament
for mapping in pending_tournament.alias_to_id_map:
try:
player_id = mapping.player_id
# TODO: reduce queries to DB by batching
player = dao.get_player_by_id(player_id)
if player.merged:
return "Player {} has already been merged".format(player.name), 400
except:
return "Not all player ids are valid", 400
try:
dao.update_pending_tournament(pending_tournament)
tournament = M.Tournament.from_pending_tournament(
pending_tournament)
tournament_id = dao.insert_tournament(tournament)
dao.delete_pending_tournament(pending_tournament)
return {"success": True, "tournament_id": str(tournament_id)}
except ValueError as e:
print e
return 'Not all player aliases in this pending tournament have been mapped to player ids.', 400
except:
return 'Dao threw an error somewhere', 400
class AddTournamentMatchResource(restful.Resource):
def get(self, region, id):
pass
def put(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
user = get_user_from_request(request, dao)
args = tournament_details_add_match_parser.parse_args()
tournament = dao.get_tournament_by_id(ObjectId(id))
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, tournament.regions):
return 'Permission denied', 403
winner_id = args['winner_id']
loser_id = args['loser_id']
if winner_id is None or loser_id is None:
print "winner and loser IDs not present. Cannot continue"
return "winner and loser IDs not present. Cannot continue", 400
try:
dao.add_match_by_tournament_id(ObjectId(id), ObjectId(winner_id), ObjectId(loser_id))
return 'Successful addition', 200
except Exception as e:
print 'error adding match to tournament: ' + str(e)
return 'error adding match to tournament: ' + str(e), 400
class ExcludeTournamentMatchResource(restful.Resource):
def get(self, region, id):
pass
def post(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
user = get_user_from_request(request, dao)
args = tournament_details_exclude_match_parser.parse_args()
try:
tournament = dao.get_tournament_by_id(ObjectId(id))
except:
return "Casting error", 400
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, tournament.regions):
return 'Permission denied', 403
match_id = int(args['match_id'])
excluded = (args['excluded_tf'].lower() == 'true')
try:
dao.set_match_exclusion_by_tournament_id_and_match_id(ObjectId(id), match_id, excluded)
except Exception as e:
print e
return 'Match exclusion failed', 400
class SwapWinnerLoserMatchResource(restful.Resource):
def get(self, region):
pass
def post(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
user = get_user_from_request(request, dao)
args = tournament_details_swap_winner_loser_parser.parse_args()
tournament_id = args['tournament_id']
match_id = int(args['match_id'])
tournament = dao.get_tournament_by_id(ObjectId(tournament_id))
if not user:
return 'Permission denied', 403
if not is_user_admin_for_regions(user, tournament.regions):
return 'Permission denied', 403
try:
dao.swap_winner_loser_by_tournament_id_and_match_id(ObjectId(tournament_id), match_id)
except Exception as e:
print e
return 'Swap Winner Loser failed.', 400
class RankingsResource(restful.Resource):
def get(self, region):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
return_dict = dao.get_latest_ranking().dump(context='web')
if not return_dict:
return 'Dao couldnt give us rankings', 400
ranking_list = []
for r in return_dict['ranking']:
player = dao.get_player_by_id(ObjectId(r['player']))
if player:
r['name'] = player.name
r['id'] = str(r.pop('player'))
ranking_list.append(r)
ranking_criteria = dao.get_region_ranking_criteria(region)
return_dict['ranking'] = ranking_list
return_dict['ranking_criteria'] = ranking_criteria
return return_dict
def put(self, region):
dao = Dao(region, mongo_client=mongo_client)
args = rankings_criteria_get_parser.parse_args()
try:
ranking_num_tourneys_attended = int(args['ranking_num_tourneys_attended'])
ranking_activity_day_limit = int(args['ranking_activity_day_limit'])
tournament_qualified_day_limit = int(args['tournament_qualified_day_limit'])
except Exception as e:
return 'Error parsing Ranking Criteria, please try again: ' + str(e), 400
print ranking_num_tourneys_attended
print ranking_activity_day_limit
if not dao:
return 'Dao not found', 404
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
if not is_user_admin_for_region(user, region):
return 'Permission denied', 403
try:
# TODO Update rankings and store criteria in db
dao.update_region_ranking_criteria(region,
ranking_num_tourneys_attended=ranking_num_tourneys_attended,
ranking_activity_day_limit=ranking_activity_day_limit,
tournament_qualified_day_limit=tournament_qualified_day_limit)
except Exception as e:
print str(e)
return 'There was an error updating the region rankings criteria', 400
return dao.get_region_ranking_criteria(region)
def post(self, region):
dao = Dao(region, mongo_client=mongo_client)
args = rankings_criteria_get_parser.parse_args()
if not dao:
return 'Dao not found', 404
user = get_user_from_request(request, dao)
if not user:
return 'Permission denied', 403
if not is_user_admin_for_region(user, region):
return 'Permission denied', 403
# we pass in now so we can mock it out in tests
now = datetime.now()
try:
try:
ranking_num_tourneys_attended = int(args['ranking_num_tourneys_attended'])
ranking_activity_day_limit = int(args['ranking_activity_day_limit'])
tournament_qualified_day_limit = int(args['tournament_qualified_day_limit'])
tournament_id_to_diff = ObjectId(args['tournament_id_to_diff'])
#TODO Get stored rankings from the db
dao.update_region_ranking_criteria(region.lower(),
ranking_num_tourneys_attended=ranking_num_tourneys_attended,
ranking_activity_day_limit=ranking_activity_day_limit,
tournament_qualified_day_limit=tournament_qualified_day_limit)
print 'Running rankings. day_limit: ' + str(ranking_activity_day_limit) + ' and num_tourneys: ' \
+ str(ranking_num_tourneys_attended) + ' and tournament_qualified_day_limit: ' + str(tournament_qualified_day_limit)
tournament_to_diff = dao.get_tournament_by_id(tournament_id_to_diff)
rankings.generate_ranking(dao, now=now,
day_limit=ranking_activity_day_limit,
num_tourneys=ranking_num_tourneys_attended,
tournament_qualified_day_limit=tournament_qualified_day_limit,
tournament_to_diff=tournament_to_diff)
except:
rankings.generate_ranking(dao, now=now)
except Exception as e:
print str(e)
return 'There was an error updating rankings', 400
return self.get(region)
class MatchesResource(restful.Resource):
def get(self, region, id):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
return 'Dao not found', 404
args = matches_get_parser.parse_args()
return_dict = {}
player = None
try:
player = dao.get_player_by_id(ObjectId(id))
except:
return 'Invalid ObjectID', 400