forked from garsh0p/garpr
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathserver.py
More file actions
1370 lines (1084 loc) · 46.9 KB
/
server.py
File metadata and controls
1370 lines (1084 loc) · 46.9 KB
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, timedelta
from flask import Flask, request, Response, jsonify
from flask.ext import restful
from flask.ext.restful import reqparse, abort
from pymongo import MongoClient
#Base logging config
import logger
import logging
logger = logging.getLogger('garpr')
import re
import sys
import traceback
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
TYPEAHEAD_PLAYER_LIMIT = 20
BASE_REGION = 'newjersey'
logging.info('Beginning server...');
# parse config file
config = Config()
mongo_client = MongoClient(host=config.get_mongo_url())
print "parsed config: ", config.get_mongo_url()
# set logger level from config
log_level = config.get_logging_level()
print "log level is set to " + str(log_level)
logger.setLevel(log_level)
app = Flask(__name__)
api = restful.Api(app)
def err(error_message, status_code=400):
# TODO: log error_message
abort(status_code, description=error_message)
def log_exception():
try:
exc_type, exc_value, exc_tb = sys.exc_info()
tb = traceback.format_exc()
logger.error(tb)
except Exception as e:
traceback.print_exc(file='garpr.unknown.error')
def get_dao(region):
dao = Dao(region, mongo_client=mongo_client)
if not dao:
err('Error connecting to DB (region {})'.format(region))
return dao
def auth_user(request, dao, check_regions=True, needs_super=False):
session_id = request.cookies.get('session_id')
user = dao.get_user_by_session_id_or_none(session_id)
if not user:
err("Permission denied", 403)
if needs_super and user.admin_level != 'SUPER':
err("Permission denied", 403)
if user.admin_level == 'REGION' and \
check_regions and \
dao.region_id not in user.admin_regions:
err("Permission denied", 403)
return user
def is_allowed_origin(origin):
dragon = r"http(s)?:\/\/(stage\.|www\.)?(notgarpr\.com|192\.168\.[^\.]+\.[^\.]+?|njssbm\.com|garpr\.com)(\:[\d]*)?$" # noqa
return re.match(dragon, origin)
def is_user_admin_for_regions(user, regions):
'''
returns true is user is an admin for ANY of the regions
'''
if user.admin_level == 'SUPER':
return True
return any(r in user.admin_regions for r in regions)
# start of URL resources
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
def post(self):
dao = get_dao(None)
auth_user(request, dao, check_regions=False, needs_super=True)
parser = reqparse.RequestParser() \
.add_argument('region_id', type=str) \
.add_argument('activeTF', type=str) \
args = parser.parse_args()
region_id = args['region_id']
activeTF = args['activeTF'].lower() == 'true'
try:
dao.update_region_activeTF(region_id, activeTF)
return 200
except Exception as e:
log_exception()
return 'Error', 400
class PlayerListResource(restful.Resource):
# returns: match_quality
# if match_quality > 0, consider it a match
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 10
# 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 5
# 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 1
# no match
return 0
def _get_players_matching_query(self, players, query):
# get list of (player, match_quality)
matching_players = [(player, self._player_matches_query(player, query)) for player in players]
# sort by most relevant matches
matching_players = sorted(
filter(lambda x: x[1] > 0, matching_players),
key=lambda x: -x[1])
# restrict to most relevant matches
matching_players = matching_players[:TYPEAHEAD_PLAYER_LIMIT]
# return player objects
return [p[0] for p in matching_players]
def get(self, region):
dao = get_dao(region)
parser = reqparse.RequestParser() \
.add_argument('alias', type=str) \
.add_argument('query', type=str) \
.add_argument('all', type=bool)
args = parser.parse_args()
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:
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 = get_dao(region)
player = None
try:
player = dao.get_player_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if not player:
err('Player not found')
return player.dump(context='web')
def put(self, region, id):
dao = get_dao(region)
auth_user(request, dao)
player = None
try:
player = dao.get_player_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if not player:
err('No player found with that region/id.')
parser = reqparse.RequestParser() \
.add_argument('name', type=str) \
.add_argument('aliases', type=list) \
.add_argument('regions', type=list)
args = 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):
err("Each alias must be a string")
new_aliases = [a.lower() for a in args['aliases']]
if player.name.lower() not in new_aliases:
err("Aliases must contain the players name!")
player.aliases = new_aliases
if args['regions'] is not None:
for a in args['regions']:
if not isinstance(a, unicode):
err("Each region must be a string")
player.regions = args['regions']
dao.update_player(player)
return player.dump(context='web')
class PlayerTournamentResource(restful.Resource):
def get(self, region, id):
dao = get_dao(None)
try:
tournament_objects = dao.get_all_player_tournaments_by_id(ObjectId(id))
tournaments = []
for t in tournament_objects:
t = t.dump(context='web')
tournaments.append(t)
return tournaments
except Exception as e:
log_exception()
print e
return 400
class PlayerSortedTournamentResource(restful.Resource):
def get(self, region, id):
dao = get_dao(None)
try:
region_sorted_tournament_counts = dao.sort_player_tournaments_by_region(ObjectId(id))
return region_sorted_tournament_counts
except Exception as e:
log_exception()
traceback.print_exc(file=sys.stdout)
print 'errrrrrrrror'
print e
return 400
class TournamentSeedResource(restful.Resource):
def post(self, region):
parser = reqparse.RequestParser() \
.add_argument('type', type=str, location='json') \
.add_argument('data', type=unicode, location='json') \
.add_argument('bracket', type=str, location='json')
args = parser.parse_args()
if args['data'] is None:
err("Data required. (TournamentSeedResource.post)")
the_bytes = bytearray(args['data'], "utf8")
if the_bytes[0] == 0xef:
err("Magic numbers! (TournamentSeedResource.post)")
type = args['type']
data = args['data']
pending_tournament = None
try:
if type == 'challonge':
scraper = ChallongeScraper(data)
else:
err("Unknown type")
pending_tournament, raw_file = M.PendingTournament.from_scraper(
type, scraper, region)
except Exception as ex:
err('Scraper encountered an error ' + str(ex))
if not pending_tournament or not raw_file:
err('Scraper encountered an error - null')
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 = get_dao(region)
parser = reqparse.RequestParser() \
.add_argument('includePending', type=str, default='false')
args = parser.parse_args()
if args['includePending'] == 'true':
auth_user(request, dao)
tournaments = dao.get_all_tournaments(regions=[region])
only_properties = ('id',
'name',
'date',
'regions',
'excluded')
# temporary fix
all_tournament_jsons = []
for t in tournaments:
try:
all_tournament_jsons.append(t.dump(context='web',
only=only_properties))
except Exception as e:
log_exception()
print 'error inserting tournament', t
if args['includePending'] == 'true':
# 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 Exception as e:
log_exception()
print 'error inserting pending tournament', p
return_dict = {}
return_dict['tournaments'] = all_tournament_jsons
return return_dict
def post(self, region):
dao = get_dao(region)
auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('type', type=str, location='json') \
.add_argument('data', type=unicode, location='json') \
.add_argument('bracket', type=str, location='json') \
.add_argument('included_phases', type=list, location='json')
args = parser.parse_args()
if args['data'] is None:
err("Tournament data required.")
the_bytes = bytearray(args['data'], "utf8")
if the_bytes[0] == 0xef:
print "found magic numbers"
err("Magic numbers!")
type = args['type']
data = args['data']
included_phases = args['included_phases']
pending_tournament = None
try:
if type == 'tio':
if args['bracket'] is None:
err("Missing bracket name")
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:
err("Unknown tournament type")
pending_tournament, raw_file = M.PendingTournament.from_scraper(
type, scraper, region)
except Exception as ex:
err('Scraper encountered an error: ' + str(ex))
if not pending_tournament or not raw_file:
err('Scraper encountered an error.')
try:
pending_tournament.alias_to_id_map = alias_service.get_alias_to_id_map_in_list_format(
dao, pending_tournament.players)
except Exception as e:
log_exception()
err('Alias service encountered an error')
# 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
err('Dao insert_raw_file encountered an error')
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:
err('Dao insert_pending_tournament encountered an error')
err('Unknown error!')
# 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 = get_dao(region)
response = None
tournament = None
try:
tournament = dao.get_tournament_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if tournament is not None:
response = convert_tournament_to_response(tournament, dao)
else:
auth_user(request, dao)
pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
if not pending_tournament:
err('Not found!')
response = pending_tournament.dump(context='web')
return response
def put(self, region, id):
dao = get_dao(region)
auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('name', type=str) \
.add_argument('date', type=str) \
.add_argument('players', type=list) \
.add_argument('matches', type=list) \
.add_argument('regions', type=list) \
.add_argument('pending', type=bool)
args = parser.parse_args()
tournament = None
try:
if args['pending']:
tournament = dao.get_pending_tournament_by_id(ObjectId(id))
else:
tournament = dao.get_tournament_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if not tournament:
err("No tournament found with that id.")
try:
if args['name']:
tournament.name = args['name']
if args['date']:
try:
tournament.date = datetime.strptime(
args['date'].strip(), '%m/%d/%y')
except Exception as e:
log_exception()
err("Invalid date format")
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, unicode):
err("each player must be a string")
tournament.players = [ObjectId(i) for i in args['players']]
tournament.orig_ids = [pid for pid in tournament.players]
if args['matches']:
for d in args['matches']:
if not isinstance(d, dict):
err("matches must be a dict")
if (not isinstance(d['winner'], unicode)) or (
not isinstance(d['loser'], unicode)):
err("winner and loser must be strings")
# turn the list of dicts into list of matchresults
matches = [M.Match(winner=ObjectId(m['winner']), loser=ObjectId(
m['loser'])) for m in args['matches']]
tournament.matches = matches
if args['regions']:
for p in args['regions']:
if not isinstance(p, unicode):
err("each region must be a string")
tournament.regions = args['regions']
except Exception as e:
log_exception()
err('Invalid ObjectID')
try:
if args['pending']:
dao.update_pending_tournament(tournament)
else:
print tournament
dao.update_tournament(tournament)
except Exception as e:
log_exception()
err('Update Tournament Error')
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 = get_dao(region)
user = auth_user(request, dao)
tournament_to_delete = None
try:
tournament_to_delete = dao.get_pending_tournament_by_id(
ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if tournament_to_delete: # its a pending tournament
if not is_user_admin_for_regions(
user, tournament_to_delete.regions):
err('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
err("No tournament (pending or finalized) found with that id.")
if not is_user_admin_for_regions(
user, tournament_to_delete.regions):
err('Permission denied')
dao.delete_tournament(tournament_to_delete)
return {"success": True}
def post(self, region, id):
"""
This post request changes a flag for the indicated tournament
determining if it is Excluded a tournament from ranking calculation
"""
dao = get_dao(region)
auth_user(request, dao)
parser = reqparse.RequestParser()
parser.add_argument('excluded_tf', type=str)
args = parser.parse_args()
excluded = (args['excluded_tf'].lower() == 'true')
try:
dao.set_tournament_exclusion_by_tournament_id(ObjectId(id), excluded)
return 200
except Exception as e:
log_exception()
return 'Error', 400
class PendingTournamentResource(restful.Resource):
"""
Currently only updates the alias_to_id_map in the pending tournament
"""
def put(self, region, id):
dao = get_dao(region)
auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('name', type=str) \
.add_argument('players', type=list) \
.add_argument('matches', type=list) \
.add_argument('regions', type=list) \
.add_argument('alias_to_id_map', type=list)
args = parser.parse_args()
pending_tournament = None
try:
pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if not pending_tournament:
err("No pending tournament found with that id.")
data = {'alias_to_id_map': [M.AliasMapping.load(
alias_item, context='web') for alias_item in args['alias_to_id_map']]}
if not data:
err('Request couldnt be converted to pending tournament')
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 Exception as e:
log_exception()
print 'Error processing alias_to_id map'
err('Error processing alias_to_id map')
try:
dao.update_pending_tournament(pending_tournament)
return pending_tournament.dump(context='web')
except Exception as e:
log_exception()
err('Encountered an error inserting pending tournament')
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 = get_dao(region)
pending_tournament = None
try:
pending_tournament = dao.get_pending_tournament_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Invalid ObjectID')
if not pending_tournament:
err('No pending tournament found with that id.')
auth_user(request, dao)
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:
err('Player {} has already been merged'.format(player.name))
except Exception as e:
log_exception()
err('Not all player ids are valid')
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
err('Not all player aliases in this pending tournament have been mapped to player ids.')
except Exception as e:
log_exception()
err('Dao threw an error somewhere')
class AddTournamentMatchResource(restful.Resource):
def get(self, region, id):
pass
def put(self, region, id):
dao = get_dao(region)
user = auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('tournament_id', type=str) \
.add_argument('winner_id', type=str) \
.add_argument('loser_id', type=str)
args = parser.parse_args()
tournament = dao.get_tournament_by_id(ObjectId(id))
if not user:
err('Permission denied', 403)
if not is_user_admin_for_regions(user, tournament.regions):
err('Permission denied', 403)
winner_id = args['winner_id']
loser_id = args['loser_id']
if winner_id is None or loser_id is None:
err("winner and loser IDs not present. Cannot continue")
try:
dao.add_match_by_tournament_id(
ObjectId(id), ObjectId(winner_id), ObjectId(loser_id))
except Exception as e:
log_exception()
print 'error adding match to tournament: ' + str(e)
err('error adding match to tournament: ' + str(e))
class ExcludeTournamentMatchResource(restful.Resource):
def get(self, region, id):
pass
def post(self, region, id):
dao = get_dao(region)
user = auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('tournament_id', type=str) \
.add_argument('match_id', type=str) \
.add_argument('excluded_tf', type=str)
args = parser.parse_args()
try:
tournament = dao.get_tournament_by_id(ObjectId(id))
except Exception as e:
log_exception()
err('Casting error')
if not is_user_admin_for_regions(user, tournament.regions):
err('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:
log_exception()
print e
err('Match exclusion failed')
class SwapWinnerLoserMatchResource(restful.Resource):
def get(self, region):
pass
def post(self, region, id):
dao = get_dao(region)
user = auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('tournament_id', type=str) \
.add_argument('match_id', type=str)
args = 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 is_user_admin_for_regions(user, tournament.regions):
err('Permission denied')
try:
dao.swap_winner_loser_by_tournament_id_and_match_id(
ObjectId(tournament_id), match_id)
except Exception as e:
log_exception()
err('Swap Winner Loser failed: ' + str(e))
class RankingsResource(restful.Resource):
def get(self, region):
dao = get_dao(region)
return_dict = dao.get_latest_ranking().dump(context='web')
if not return_dict:
err('Dao couldnt give us rankings')
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 = get_dao(region)
auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('ranking_activity_day_limit', type=str) \
.add_argument('ranking_num_tourneys_attended', type=str) \
.add_argument('tournament_qualified_day_limit', type=str)
args = 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:
log_exception()
err('Error parsing Ranking Criteria, please try again: ' + str(e))
print ranking_num_tourneys_attended
print ranking_activity_day_limit
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:
log_exception()
err('There was an error updating the region rankings criteria:' + str(e))
return dao.get_region_ranking_criteria(region)
def post(self, region):
dao = get_dao(region)
auth_user(request, dao)
parser = reqparse.RequestParser() \
.add_argument('ranking_activity_day_limit', type=str) \
.add_argument('ranking_num_tourneys_attended', type=str) \
.add_argument('tournament_qualified_day_limit', type=str)
args = parser.parse_args()
# 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'])
# 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)
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)
except Exception as e:
log_exception()
rankings.generate_ranking(dao, now=now)
except Exception as e:
log_exception()
print str(e)
err('There was an error updating rankings')
return self.get(region)
class MatchesResource(restful.Resource):
def get(self, region, id):
dao = get_dao(region)
parser = reqparse.RequestParser() \
.add_argument('opponent', type=str)
args = parser.parse_args()
return_dict = {}
player = None
try:
player = dao.get_player_by_id(ObjectId(id))
except Exception as e:
log_exception()
logger.error(e)
err('Invalid ObjectID')
return_dict['player'] = {'id': str(player.id), 'name': player.name}
player_list = [player]
opponent_id = args['opponent']
if opponent_id is not None:
try:
opponent = dao.get_player_by_id(ObjectId(args['opponent']))
return_dict['opponent'] = {