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
|
import copy
import inspect
from urlparse import urljoin
from jfr_playoff.dto import Match, Team
from jfr_playoff.logger import PlayoffLogger
class ResultInfoClient(object):
def __init__(self, settings, database=None):
self.settings = settings
self.database = database
@property
def priority(self):
return 0
def is_capable(self):
return False
def get_exceptions(self, method):
pass
class ResultInfo(object):
def __init__(self, *args):
self.clients = self._fill_client_list(*args)
@property
def submodule_path(self):
raise NotImplementedError()
@property
def _client_classes(self):
module = __import__(self.submodule_path, fromlist=[''])
for submodule_path in module.CLIENTS:
submodule = __import__(submodule_path, fromlist=[''])
for member in inspect.getmembers(submodule, inspect.isclass):
if member[1].__module__ == submodule_path:
yield member[1]
def _fill_client_list(self, *args):
all_clients = [c(*args) for c in self._client_classes]
clients = [c for c in all_clients if c.is_capable()]
return sorted(clients, key=lambda c: c.priority, reverse=True)
def call_client(self, method, default, *args):
PlayoffLogger.get('resultinfo').info(
'calling %s on result info clients', method)
for client in self.clients:
try:
ret = getattr(client, method)(*args)
PlayoffLogger.get('resultinfo').info(
'%s.%s method returned %s',
client.__class__.__name__, method, ret)
return ret
except Exception as e:
if type(e) \
in client.get_exceptions(method) + (NotImplementedError,):
PlayoffLogger.get('resultinfo').warning(
'%s.%s method raised %s(%s)',
client.__class__.__name__, method,
type(e).__name__, str(e))
else:
raise
PlayoffLogger.get('resultinfo').info(
'%s method returning default: %s', method, default)
return default
class TournamentInfo(ResultInfo):
def __init__(self, settings, database):
ResultInfo.__init__(self, settings, database)
self.final_positions = settings.get('final_positions', [])
@property
def submodule_path(self):
return 'jfr_playoff.data.tournament'
def get_tournament_results(self):
teams = self.call_client('get_tournament_results', [])
if self.is_finished():
PlayoffLogger.get('tournamentinfo').info(
'setting final positions from tournament results: %s',
self.final_positions)
for position in self.final_positions:
if len(teams) >= position:
teams[position-1] = (teams[position-1] + [None] * 4)[0:4]
teams[position-1][3] = position
return teams
def is_finished(self):
return self.call_client('is_finished', True)
def get_results_link(self, suffix='leaderb.html'):
return self.call_client('get_results_link', None, suffix)
class MatchInfo(ResultInfo):
matches = {}
def __init__(self, match_config, teams, database, aliases=None):
ResultInfo.__init__(self, match_config, database)
self.config = match_config
self.teams = teams
self.database = database
self.aliases = {}
if aliases:
for team, team_aliases in aliases.iteritems():
for alias in team_aliases:
self.aliases[alias] = team
self.info = Match()
self._init_info()
self._fetch_match_link()
@property
def submodule_path(self):
return 'jfr_playoff.data.match'
def _init_info(self):
self.info.id = self.config['id']
MatchInfo.matches[self.info.id] = self.info
self.info.running = 0
self.info.winner_matches = []
self.info.loser_matches = []
for i in range(0, 2):
if 'winner' in self.config['teams'][i]:
self.info.winner_matches += self.config['teams'][i]['winner']
if 'loser' in self.config['teams'][i]:
self.info.loser_matches += self.config['teams'][i]['loser']
self.info.winner_matches = list(set(self.info.winner_matches))
self.info.loser_matches = list(set(self.info.loser_matches))
self.info.winner_place = self.config.get('winner', [])
self.info.loser_place = self.config.get('loser', [])
self.info.teams = []
def _fetch_match_link(self):
link = self.call_client('get_match_link', None)
if link is not None:
self.info.link = link
else:
PlayoffLogger.get('matchinfo').info(
'match #%d link empty', self.info.id)
def _get_predefined_scores(self):
teams = [Team(), Team()]
scores_fetched = False
teams_fetched = False
if 'score' in self.config:
i = 0
for score in self.config['score']:
if isinstance(self.config['score'], dict):
teams[i].score = self.config['score'][score]
try:
team_no = int(score)
teams[i].name = [self.teams[team_no-1][0]]
except ValueError:
teams[i].name = [score]
teams_fetched = True
else:
teams[i].score = score
i += 1
if i == 2:
break
scores_fetched = True
PlayoffLogger.get('matchinfo').info(
'pre-defined scores for match #%d: %s',
self.info.id, teams)
return scores_fetched, teams_fetched, teams
def _get_config_teams(self, teams):
for i in range(0, 2):
match_teams = []
possible_teams = []
if isinstance(self.config['teams'][i], basestring):
match_teams = [self.config['teams'][i]]
elif isinstance(self.config['teams'][i], list):
match_teams = self.config['teams'][i]
else:
if 'winner' in self.config['teams'][i]:
match_teams += [
MatchInfo.matches[winner_match].winner
for winner_match in self.config['teams'][i]['winner']]
possible_teams += [
MatchInfo.matches[winner_match].possible_winner
for winner_match in self.config['teams'][i]['winner']]
if 'loser' in self.config['teams'][i]:
match_teams += [
MatchInfo.matches[loser_match].loser
for loser_match in self.config['teams'][i]['loser']]
possible_teams += [
MatchInfo.matches[loser_match].possible_loser
for loser_match in self.config['teams'][i]['loser']]
if 'place' in self.config['teams'][i]:
match_teams += [
self.teams[place-1][0]
for place in self.config['teams'][i]['place']]
teams[i].name = match_teams
teams[i].possible_name = possible_teams
teams[i].known_teams = len([
team for team in match_teams if team is not None])
teams[i].selected_team = self.config['selected_teams'][i] \
if 'selected_teams' in self.config else -1
PlayoffLogger.get('matchinfo').info(
'config scores for match #%d: %s',
self.info.id, teams)
return teams
def _resolve_team_aliases(self, teams):
return [
self.aliases[team]
if team in self.aliases
else team
for team in teams]
def _fetch_teams_with_scores(self):
(scores_fetched, teams_fetched, self.info.teams) = \
self._get_predefined_scores()
if scores_fetched:
self.info.running = int(self.config.get('running', -1))
if not teams_fetched:
teams = self.call_client(
'fetch_teams', None,
copy.deepcopy(self.info.teams))
if teams is None:
PlayoffLogger.get('matchinfo').warning(
'fetching teams for match #%d failed, reverting to config',
self.info.id)
self.info.teams = self._get_config_teams(self.info.teams)
else:
self.info.teams = teams
for team in range(0, len(self.info.teams)):
if isinstance(self.config['teams'][team], dict):
self.info.teams[team].place = self.config['teams'][team].get(
'place', self.info.teams[team].place)
self.info.teams[team].name = self._resolve_team_aliases(
self.info.teams[team].name)
PlayoffLogger.get('matchinfo').info(
'team list after resolving aliases: %s',
self.info.teams[team].name)
self.info.teams[team].possible_name = self._resolve_team_aliases(
self.info.teams[team].possible_name)
PlayoffLogger.get('matchinfo').info(
'predicted team list after resolving aliases: %s',
self.info.teams[team].possible_name)
def _fetch_board_count(self):
boards_played, boards_to_play = self.call_client(
'board_count', (0, 0))
if boards_played > 0:
self.info.running = -1 \
if boards_played >= boards_to_play \
else boards_played
def _determine_outcome(self):
if (self.info.teams[0].known_teams == 1) \
and (self.info.teams[1].known_teams == 1):
if self.info.running == -1:
if self.info.teams[0].score > self.info.teams[1].score:
self.info.winner = self.info.teams[0].name[0]
self.info.loser = self.info.teams[1].name[0]
else:
self.info.loser = self.info.teams[0].name[0]
self.info.winner = self.info.teams[1].name[0]
elif self.info.running > 0:
if self.info.teams[0].score > self.info.teams[1].score:
self.info.possible_winner = self.info.teams[0].name[0]
self.info.possible_loser = self.info.teams[1].name[0]
elif self.info.teams[0].score < self.info.teams[1].score:
self.info.possible_loser = self.info.teams[0].name[0]
self.info.possible_winner = self.info.teams[1].name[0]
def _determine_running_link(self):
if self.info.link is None:
return
self.info.link = self.call_client('running_link', self.info.link)
def set_phase_link(self, phase_link):
prev_link = self.info.link
if self.info.link is None:
self.info.link = phase_link
else:
if self.info.link != '#':
self.info.link = urljoin(phase_link, self.info.link)
PlayoffLogger.get('matchinfo').info(
'applying phase link %s to match #%d: %s',
phase_link, self.info.id, self.info.link)
# re-init result info clients
if (prev_link != self.info.link) and (self.info.link is not None):
PlayoffLogger.get('matchinfo').info(
'config link changed, re-initializing result info client list')
self.config['link'] = self.info.link
ResultInfo.__init__(self, self.config, self.database)
def get_info(self):
self._fetch_teams_with_scores()
self._fetch_board_count()
self._determine_outcome()
if self.info.running > 0:
self._determine_running_link()
return self.info
|