forked from garsh0p/garpr
-
Notifications
You must be signed in to change notification settings - Fork 14
/
model.py
381 lines (304 loc) · 14.6 KB
/
model.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
from bson.objectid import ObjectId
import trueskill
import orm
SOURCE_TYPE_CHOICES = ('tio', 'challonge', 'smashgg', 'other')
ADMIN_LEVEL_CHOICES = ('REGION', 'SUPER')
# Embedded documents
class AliasMapping(orm.Document):
collection_name = None
fields = [('player_id', orm.ObjectIDField()),
('player_alias', orm.StringField(required=True))]
class AliasMatch(orm.Document):
collection_name = None
fields = [('winner', orm.StringField(required=True)),
('loser', orm.StringField(required=True))]
class Match(orm.Document):
collection_name = None
fields = [('match_id', orm.IntField(required=True)),
('winner', orm.ObjectIDField(required=True)),
('loser', orm.ObjectIDField(required=True)),
('excluded', orm.BooleanField(required=True, default=False))]
def __str__(self):
return "%s > %s" % (self.winner, self.loser)
def contains_players(self, player1, player2):
return (self.winner == player1 and self.loser == player2) or \
(self.winner == player2 and self.loser == player1)
def contains_player(self, player_id):
return self.winner == player_id or self.loser == player_id
def did_player_win(self, player_id):
return self.winner == player_id
def get_opposing_player_id(self, player_id):
if self.winner == player_id:
return self.loser
elif self.loser == player_id:
return self.winner
else:
return None
class RankingEntry(orm.Document):
collection_name = None
fields = [('player', orm.ObjectIDField(required=True)),
('rank', orm.IntField(required=True)),
('rating', orm.FloatField(required=True))]
class Rating(orm.Document):
collection_name = None
fields = [('mu', orm.FloatField(required=True, default=25.)),
('sigma', orm.FloatField(required=True, default=25. / 3))]
def trueskill_rating(self):
return trueskill.Rating(mu=self.mu, sigma=self.sigma)
@classmethod
def from_trueskill(cls, trueskill_rating):
return Rating(mu=trueskill_rating.mu,
sigma=trueskill_rating.sigma)
# MongoDB collection documents
MONGO_ID_SELECTOR = {'db': '_id',
'web': 'id'}
class Player(orm.Document):
collection_name = 'players'
fields = [('id', orm.ObjectIDField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('name', orm.StringField(required=True)),
('aliases', orm.ListField(orm.StringField())),
('ratings', orm.DictField(orm.StringField(), orm.DocumentField(Rating))),
('regions', orm.ListField(orm.StringField())),
('merged', orm.BooleanField(required=True, default=False)),
('merge_parent', orm.ObjectIDField()),
('merge_children', orm.ListField(orm.ObjectIDField()))
]
def validate_document(self):
# check: merged is True <=> merge_parent is not None
if self.merged and self.merge_parent is None:
return False, "player is merged but has no parent"
if self.merge_parent is not None and not self.merged:
return False, "player has merge_parent but is not merged"
return True, None
def post_init(self):
# initialize merge_children to contain id if it does not already
if not self.merge_children:
self.merge_children = [self.id]
# if aliases empty add name to aliases
if not self.aliases:
self.aliases = [self.name.lower()]
@classmethod
def create_with_default_values(cls, name, region):
return cls(id=ObjectId(),
name=name,
aliases=[name.lower()],
ratings={},
regions=[region])
class Tournament(orm.Document):
collection_name = 'tournaments'
fields = [('id', orm.ObjectIDField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('name', orm.StringField(required=True)),
('type', orm.StringField(
required=True,
validators=[orm.validate_choices(SOURCE_TYPE_CHOICES)])),
('date', orm.DateTimeField()),
('regions', orm.ListField(orm.StringField())),
('url', orm.StringField()),
('raw_id', orm.ObjectIDField()),
('matches', orm.ListField(orm.DocumentField(Match))),
('players', orm.ListField(orm.ObjectIDField())),
('orig_ids', orm.ListField(orm.ObjectIDField())),
('excluded', orm.BooleanField(default=False))]
def validate_document(self):
# check: set of players in players = set of players in matches
players_ids = {player for player in self.players}
matches_ids = {match.winner for match in self.matches} | \
{match.loser for match in self.matches}
if players_ids != matches_ids:
return False, "set of players in players differs from set of players in matches"
# check: no one plays themselves
for match in self.matches:
if match.winner == match.loser:
return False, "tournament contains match where player plays themself"
# check: len of orig_ids should equal len of players
if len(self.orig_ids) != len(self.players):
return False, "different number of orig_ids and players"
return True, None
def post_init(self):
# if orig_ids empty, set to players
if not self.orig_ids:
self.orig_ids = [player for player in self.players]
def replace_player(self, player_to_remove=None, player_to_add=None):
if player_to_remove is None or player_to_add is None:
raise TypeError(
"player_to_remove and player_to_add cannot be None!")
player_to_remove_id = player_to_remove.id
player_to_add_id = player_to_add.id
if player_to_remove_id not in self.players:
print "Player with id %s is not in this tournament. Ignoring." % player_to_remove.id
return
self.players.remove(player_to_remove_id)
self.players.append(player_to_add_id)
for match in self.matches:
if match.winner == player_to_remove_id:
match.winner = player_to_add_id
if match.loser == player_to_remove_id:
match.loser = player_to_add_id
@classmethod
def from_pending_tournament(cls, pending_tournament):
# takes a real alias to id map instead of a list of objects
def _get_player_id_from_map_or_throw(alias_to_id_map, alias):
if alias in alias_to_id_map:
return alias_to_id_map[alias]
else:
raise ValueError('Alias %s has no ID in map\n: %s' %
(alias, alias_to_id_map))
alias_to_id_map = dict([(entry.player_alias, entry.player_id)
for entry in pending_tournament.alias_to_id_map
if entry.player_id is not None])
# we need to convert pending tournament players/matches to player IDs
print pending_tournament.players, pending_tournament.matches
players = [_get_player_id_from_map_or_throw(
alias_to_id_map, p) for p in pending_tournament.players]
matches = []
counter = 0
for am in pending_tournament.matches:
m = Match(
match_id=counter,
winner=_get_player_id_from_map_or_throw(
alias_to_id_map, am.winner),
loser=_get_player_id_from_map_or_throw(
alias_to_id_map, am.loser),
excluded=False
)
matches.append(m)
counter+=1
excluded = False
return cls(
id=pending_tournament.id,
name=pending_tournament.name,
type=pending_tournament.type,
date=pending_tournament.date,
regions=pending_tournament.regions,
url=pending_tournament.url,
raw_id=pending_tournament.raw_id,
matches=matches,
players=players,
orig_ids=players,
excluded=excluded)
class PendingTournament(orm.Document):
collection_name = 'pending_tournaments'
fields = [('id', orm.ObjectIDField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('name', orm.StringField(required=True)),
('type', orm.StringField(required=True)),
('date', orm.DateTimeField()),
('regions', orm.ListField(orm.StringField())),
('url', orm.StringField()),
('raw_id', orm.ObjectIDField()),
('matches', orm.ListField(orm.DocumentField(AliasMatch))),
('players', orm.ListField(orm.StringField())),
('alias_to_id_map', orm.ListField(orm.DocumentField(AliasMapping))),
('excluded', orm.BooleanField(default=False))]
def validate_document(self):
# check: set of aliases = set of aliases in matches
players_aliases = set(self.players)
matches_aliases = {match.winner for match in self.matches} | \
{match.loser for match in self.matches}
mapping_aliases = {mapping.player_alias for mapping in self.alias_to_id_map}
if players_aliases != matches_aliases:
return False, "set of players in players differs from set of players in matches"
# check: set of aliases in mapping is subset of player aliases
if not mapping_aliases.issubset(players_aliases):
return False, "alias mappings contain mapping for alias not in tournament"
return True, None
def set_alias_id_mapping(self, alias, id):
if self.alias_to_id_map is None:
self.alias_to_id_map = []
for mapping in self.alias_to_id_map:
if mapping.player_alias == alias:
mapping.player_alias = alias
mapping.player_id = id
return
# if we've gotten out here, we couldn't find an existing match, so add
# a new element
self.alias_to_id_map.append(AliasMapping(
player_alias=alias,
player_id=id
))
def delete_alias_id_mapping(self, alias):
if self.alias_to_id_map is None:
self.alias_to_id_map = []
for mapping in self.alias_to_id_map:
if mapping.player_alias == alias:
self.alias_to_id_map.remove(mapping)
return mapping
@classmethod
def from_scraper(cls, type, scraper, region_id):
raw_file = RawFile(id=ObjectId(),
data=str(scraper.get_raw()))
pending_tournament = cls(
id=ObjectId(),
name=scraper.get_name(),
type=type,
date=scraper.get_date(),
regions=[region_id],
url=scraper.get_url(),
raw_id=raw_file.id,
players=scraper.get_players(),
matches=scraper.get_matches())
# check if scraper returned valid pending tournament:
valid, errors = pending_tournament.validate()
if not valid:
print "ERROR:", errors
print pending_tournament.url
# for scrapers that may return some extra players not in matches
# remove these players:
pending_tournament.players = list(
{match.winner for match in pending_tournament.matches} | \
{match.loser for match in pending_tournament.matches})
return pending_tournament, raw_file
# used to store large blobs of data (e.g. raw tournament data) so we don't
# need to carry around tournament data as much. (might eventually be replaced
# with something like S3)
class RawFile(orm.Document):
collection_name = 'raw_files'
fields = [('id', orm.ObjectIDField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('data', orm.StringField())]
class Ranking(orm.Document):
collection_name = 'rankings'
fields = [('id', orm.ObjectIDField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('region', orm.StringField(required=True)),
('tournaments', orm.ListField(orm.ObjectIDField())),
('time', orm.DateTimeField()),
('ranking', orm.ListField(orm.DocumentField(RankingEntry)))]
class Region(orm.Document):
collection_name = 'regions'
fields = [('id', orm.StringField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('display_name', orm.StringField(required=True)),
('ranking_num_tourneys_attended', orm.IntField(required=True, default=2)),
('ranking_activity_day_limit', orm.IntField(required=True, default=60)),
('tournament_qualified_day_limit', orm.IntField(required=True, default=999)),
('activeTF', orm.BooleanField(required=True, default=True))]
class User(orm.Document):
collection_name = 'users'
fields = [('id', orm.StringField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('username', orm.StringField(required=True)),
('salt', orm.StringField(required=True)),
('hashed_password', orm.StringField(required=True)),
('admin_regions', orm.ListField(orm.StringField())),
('admin_level', orm.StringField(required=True, default='REGION',
validators=[orm.validate_choices(ADMIN_LEVEL_CHOICES)])
)]
class Merge(orm.Document):
collection_name = 'merges'
fields = [('id', orm.ObjectIDField(required=True, load_from=MONGO_ID_SELECTOR,
dump_to=MONGO_ID_SELECTOR)),
('requester_user_id', orm.StringField()),
('source_player_obj_id', orm.ObjectIDField(required=True)),
('target_player_obj_id', orm.ObjectIDField(required=True)),
('time', orm.DateTimeField())]
def validate_document(self):
if self.source_player_obj_id == self.target_player_obj_id:
return False, "source and target must be different"
return True, None
class Session(orm.Document):
collection_name = 'sessions'
fields = [('session_id', orm.StringField(required=True)),
('user_id', orm.StringField(required=True))]