]> git.sesse.net Git - ultimatescore/blob - update_sheets.js
Restructure config for ranking lists a bit.
[ultimatescore] / update_sheets.js
1 // Updates back to the Google spreadsheet.
2 // There's basically zero error handling here, but OK, missing some updates is fine, really.
3
4 let jwt_key = {
5         "type": "service_account",
6         "project_id": "solskogen-cubemap",
7         "private_key_id": "9eaf56bb4d6b688c3c73bd532fecdde943eea718",
8         "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCPlcoZuj+tiaiw\nH5tjcZmCAFuCS3LhND+4WgA7BPvA3yrHvgm23T9aYVhhntA/uv2MSNjbZLj9Bk5z\nTfhSF6X6mr6JdtK05X5FXOiZdk8/36FT+aLANFqhyTD4WGXQVaHVjp1i6YNm9NvH\nUCt+R99VSteuvEyMQbqQtqTgTAisCmiO6bMssK90xKH9hwc5Zew/OUEaxa+ivgPR\nbgD3cTTQrPh0SKrZQFvdxx9ikGI/7rTZUazGU8r+VHBRCTMExCx1uQa2QzMd3REM\nngQCQ9TIkS0fNsE6NE8omrbbDJK1ob5tm4Jm6O7a7cN+yCel8sWoqW4fHdUb1z5n\n9IOUgHgFAgMBAAECggEAAWYJL2scghpvzbNf+JlbdO1a9tRvvIaK+cbvOBGqST7e\nqynVf2O0KqEh91MsMIq6O/Gl/fWns1fPBoc10zZOwcnugeb8LbcLZwlqtbtjo8wi\nV8sgn1kVfKDwjvT/LyuHgPI7mqbTxp7iGN36ZnnZLB9wkxjJKBe6YPznl8yROeoK\n4BdLaTWSv5w9mp1wnPG5RVsS5oAkoSFyDY0U7gAetsUjNf7bdlGtLvobw3kOpa7W\nm8WdN6jGbbyxmpe5Ql66/DhTBI4giNDDVvhf6fcRCOO+aAWNzZ5R6SgrdSYHbuBQ\npzGI7nBmBg3Nu1EYpm42wrUpoh6czy1Uf0F6VDmIkQKBgQDEh1Ado/QICWGQu6MB\nP0tX+APhN10x9Oq511Fd9SnTLZz2yzUN5Sshor+nevpes1Ljf8hS2FSV0fl0nRg3\nb7uMRt6EZNmzJJlPCQeBHNevVg5Z3kn3cpGE2cIr5JWB3r+EVd9wTOz7ihOVOboY\nt0yREiMeRuVmrwPi98hyoaNiHQKBgQC7CQzLGUHQDORBlQA0V6NFyamgrpkbSdML\nIZ3VThxbSxFGROC6W8At914F3XXTeP4f/kU1jjYOYhKpQy2RpOg6oLyCIx78sC/J\nkZS5eMeqv/hLSLt5eebAx0tVpDO++z/MWbbr/EpPMwQlSMMFlU2HqUK3XnAlSv9Q\njBxrs1sJCQKBgGy1GFi85vBHGCOx1rGK7EcllifOsws+GVRgyM47HT6FvYw5zQf5\nmokJeA/RE4qskI3skcdZiDgzJFQfzVRkxo4KaW08R7sy5GZ2bSM67Ac9h8SoE6v/\nQIUG2sPitdxXdQJjaau5sWBV+Q0TGGAxi/W23ZwSxTOuXWz/eG4IANL1AoGBAJdc\nmpLejMk/NZXxbGnvpn161yDnS5au5vEyMlYGUaJ8HK2+XhPS3rMUZm3erFUIrLfd\ngcr2nL6FFc8PQ5iDWUDhBc1XeONL/lBk1XRHz2Za1yit4rJLObg3ULstGIdtM1NA\nI23VDZoMkkVOHi2th0HLc+eLsLwtdnOMABAU5Q5pAoGBAKoZY3MflCEIj1S2hKQB\ncmz68DcwwXiwwuwE4zXoTWO95xApl7IP9ElNr1LFjYEhRp0VKyeZJ8UASKLN0nKF\ncD36qa71rd9VvKsNOiiKwbNy/E9WQ2B5rfovPbg2xSr8AQJxwZww2iv0zsP/Z+fG\nWYKJbvIPySmSrXhg9seBoSOL\n-----END PRIVATE KEY-----\n",
9         "client_email": "ultimate-nm-2018@solskogen-cubemap.iam.gserviceaccount.com",
10         "client_id": "102636658655884526659",
11         "auth_uri": "https://accounts.google.com/o/oauth2/auth",
12         "token_uri": "https://accounts.google.com/o/oauth2/token",
13         "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
14         "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ultimate-nm-2018%40solskogen-cubemap.iam.gserviceaccount.com"
15 };
16
17 function post_data(url, contents, content_type, cb, auth) {
18         let req = new XMLHttpRequest();
19         req.onload = function(e) {
20                 cb(req.responseText);
21         };
22         req.open('POST', url);
23         req.setRequestHeader("Content-type", content_type);
24         if (auth !== undefined) {
25                 req.setRequestHeader("Authorization", "Bearer " + auth);
26         }
27         req.send(contents);
28 }
29
30 function post_json(url, json, cb, auth) {
31         post_data(url, JSON.stringify(json), "application/json;charset=UTF-8", cb, auth);
32 }
33
34 let current_oauth_access_token = null;
35 let oauth_expire = 0;
36
37 function update_oauth_key(cb) {
38         let now = Math.floor(new Date().getTime() / 1000);
39         let jwt = {
40                 "iss": jwt_key.client_email,
41                 "scope": "https://www.googleapis.com/auth/spreadsheets",
42                 "aud":"https://www.googleapis.com/oauth2/v4/token",
43                 "exp": now + 1800,
44                 "iat": now,
45         };
46         let sJWS = KJUR.jws.JWS.sign(null, {"alg": "RS256"}, jwt, jwt_key.private_key);
47         post_data('https://www.googleapis.com/oauth2/v4/token',
48                 "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + sJWS,
49                 "application/x-www-form-urlencoded",
50                 function(response) {
51                         current_oauth_access_token = JSON.parse(response)['access_token'];
52                         console.log("Got new OAuth key.");
53                         oauth_expire = now + 1800;
54                         if (cb !== undefined) { cb(); }
55                 });
56 }
57
58 function possibly_update_oauth_key(cb) {
59         let now = Math.floor(new Date().getTime() / 1000);
60         if (oauth_expire - now < 60) {
61                 console.log("Getting new OAuth key...");
62                 update_oauth_key(cb);
63         } else {
64                 cb();
65         }
66 }
67
68 function publish_group_rank(response, group_name)
69 {
70         let updates = [];
71         let config = ultimateconfig['group_cells'][group_name];
72         let cols = config['score_sheet_cols'];
73
74         let teams = parse_teams_from_spreadsheet(response);
75         let games = parse_games_from_spreadsheet(response, group_name, false);
76         apply_games_to_teams(games, teams);
77
78         // Write the points total to the unsorted columns.
79         if (config['point_total_start_row'] !== null) {
80                 for (let i = 0; i < teams.length; ++i) {
81                         let row = config['point_total_start_row'] + i;
82                         updates.push({ "range": cols[2] + row, "values": [ [ teams[i].pts ] ] });
83                 }
84         }
85
86         let tiebreakers = [];
87         teams = rank(games, teams, 1, tiebreakers);
88
89         // Write the ranking table, from scratch.
90         for (let i = 0; i < teams.length; ++i) {
91                 let row = config['ranking_list_start_row'] + i;
92                 updates.push({ "range": cols[0] + row, "values": [ [ teams[i].rank ] ] });
93                 updates.push({ "range": cols[1] + row, "values": [ [ teams[i].mediumname ] ] });
94                 updates.push({ "range": cols[2] + row, "values": [ [ teams[i].pts ] ] });
95         }
96
97         let tb_str = "";
98         if (tiebreakers.length != 0) {
99                 tb_str = tiebreakers.join("\n");
100         }
101         updates.push({ "range": cols[0] + config['ranking_list_explain_row'], "values": [ [ tb_str ] ]});
102
103         let json = {
104                 "valueInputOption": "USER_ENTERED",
105                 "data": updates 
106         };
107         possibly_update_oauth_key(function() {
108                 post_json('https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values:batchUpdate?key=' + ultimateconfig['api_key'], json, function(response) {}, current_oauth_access_token);
109         });
110 }
111
112 function montecarlo(responses) {
113         let pseudo_group_names = ['X', 'Y', 'Z'];
114         let real_group_names = ['A', 'B', 'C'];
115         let teams = [], games = [], teams_to_idx = [];
116
117         let third_groups = [];
118         let busted_thirds = false;
119
120         for (const response of responses) {
121                 let teams_group = parse_teams_from_spreadsheet(response);
122                 let games_group = parse_games_from_spreadsheet(response, 'irrelevant group name', true);
123                 apply_games_to_teams(games_group, teams_group);
124
125                 teams.push(teams_group);
126                 games.push(games_group);
127                 teams_to_idx.push(make_teams_to_idx(teams_group));
128         }
129
130         for (let simulation_idx = 0; simulation_idx < 100; ++simulation_idx) {  // 100 seems to be enough.
131                 let thirds = [];
132                 for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
133                         // Fill in random results. We deliberately use a uniform [-13,+13]
134                         // model here, since we are interested in the extremal results.
135                         // Of course, not all real games go to 13, but the risk of that
136                         // influencing the tiebreakers is very slim.
137                         let games_copy = [];
138                         for (const game of games[group_idx]) {
139                                 games_copy.push(Object.assign({}, game));
140                         }
141                         let teams_copy = [];
142                         for (const team of teams[group_idx]) {
143                                 teams_copy.push(Object.assign({}, team));
144                         }
145
146                         for (let i = 0; i < games_copy.length; ++i) {
147                                 let idx1 = teams_to_idx[group_idx][games_copy[i].name1];
148                                 let idx2 = teams_to_idx[group_idx][games_copy[i].name2];
149                                 if (idx1 === undefined || idx2 === undefined) continue;
150                                 if (games_copy[i].score1 === undefined || games_copy[i].score2 === undefined ||
151                                     isNaN(games_copy[i].score1) || isNaN(games_copy[i].score2) ||
152                                     games_copy[i].score1 == games_copy[i].score2) {
153                                         // These were skipped by apply_games_to_teams() above.
154                                         let score1 = 0, score2 = 0;
155                                         let r = Math.floor(Math.random() * 26);
156                                         if (r < 13) {
157                                                 score1 = 13;
158                                                 score2 = r;
159                                                 teams_copy[idx1].pts += 2;
160                                         } else {
161                                                 score1 = r - 13;
162                                                 score2 = 13;
163                                                 teams_copy[idx2].pts += 2;
164                                         }
165                                         games_copy[i].score1 = score1;
166                                         games_copy[i].score2 = score2;
167                                         ++teams_copy[idx1].nplayed;
168                                         ++teams_copy[idx2].nplayed;
169                                         teams_copy[idx1].goals += score1;
170                                         teams_copy[idx2].goals += score2;
171                                         teams_copy[idx1].gd += score1;
172                                         teams_copy[idx2].gd += score2;
173                                         teams_copy[idx1].gd -= score2;
174                                         teams_copy[idx2].gd -= score1;
175                                 } else {
176                                         continue;
177                                 }
178                         }
179                         
180                         // Now rank according to the simulation.
181                         let tiebreakers = [];
182                         teams_copy = rank(games_copy, teams_copy, 1, tiebreakers);
183
184                         // See if we have conflicting information with other simulations.
185                         if (simulation_idx == 0) {
186                                 for (let i = 0; i < teams[group_idx].length; ++i) {
187                                         let idx = teams_to_idx[group_idx][teams_copy[i].name];
188                                         teams[group_idx][idx].simulated_rank = teams_copy[i].rank;
189                                 }
190                         } else {
191                                 for (let i = 0; i < teams[group_idx].length; ++i) {
192                                         let idx = teams_to_idx[group_idx][teams_copy[i].name];
193                                         if (teams[group_idx][idx].simulated_rank !== teams_copy[i].rank) {
194                                                 teams[group_idx][idx].simulated_rank = null;
195                                         }
196                                 }
197                         }
198
199                         if (!busted_thirds) {
200                                 let any_third_found = false;
201                                 for (let i = 0; i < teams[group_idx].length; ++i) {
202                                         // Store the third.
203                                         if (i == 2 || teams_copy[i].rank == 3) {
204                                                 if (any_third_found) {
205                                                         busted_thirds = true;
206                                                 } else {
207                                                         teams_copy[i].group_idx = group_idx;
208                                                         thirds.push(teams_copy[i]);
209                                                         any_third_found = true;
210                                                 }
211                                         }
212                                 }
213                         }
214                 }
215
216                 // Also rank thirds.
217                 if (!busted_thirds) {
218                         let tiebreakers = [];
219                         let ranked = rank_thirds([], thirds, 1, tiebreakers);
220                         if (simulation_idx == 0) {
221                                 third_groups = ranked;
222                         } else {
223                                 for (let i = 0; i < responses.length; ++i) {
224                                         if (third_groups[i].group_idx !== ranked[i].group_idx) {
225                                                 third_groups[i].group_idx = null;
226                                         }
227                                 }
228                         }
229                 }
230         }
231
232         let replacements = [];
233         for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
234                 if (third_groups[group_idx].group_idx !== null) {
235                         replacements.push([ pseudo_group_names[group_idx], real_group_names[third_groups[group_idx].group_idx] ]);
236                 }
237         }
238
239         for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
240                 for (let i = 0; i < teams[group_idx].length; ++i) {
241                         if (teams[group_idx][i].simulated_rank !== null) {
242                                 replacements.push([ real_group_names[group_idx] + teams[group_idx][i].simulated_rank, teams[group_idx][i].shortname ]);
243                         }
244                 }
245         }
246
247         return replacements;
248 }
249
250 function names_for_team(team, expansions) {
251         if (expansions.hasOwnProperty(team)) {
252                 return expansions[team];
253         }
254         let longteam = team.replace("W ", "Win. ").replace("L ", "Los. ");
255         return [ longteam, longteam, team ];
256 }
257
258 function expand_mediumname_if_single_team(team, expansions) {
259         if (expansions.hasOwnProperty(team)) {
260                 return expansions[team][1];
261         }
262         return team;
263 }
264
265 function do_replacements(str, replacements) {
266         for (const r of replacements) {
267                 str = str.replace(r[0], r[1]);
268         }
269         return str;
270 }
271
272 function fill_playoff(replacements, teams) {
273         let team_expansions = {};
274         for (const group of teams) {
275                 for (const team of group) {
276                         team_expansions[team.name] = team_expansions[team.mediumname] = team_expansions[team.shortname] =
277                                 [ team.name, team.mediumname, team.shortname ];
278                 }
279         }
280
281         let games = ultimateconfig['playoff_games'];
282         get_results('Results', function(response) {
283                 let updates = [], meta_updates = [];
284                 let game_num = 0;
285                 for (const game of games) {
286                         let team1 = do_replacements(game[0], replacements);
287                         let team2 = do_replacements(game[1], replacements);
288                         let team1_mediumname = expand_mediumname_if_single_team(team1, team_expansions);
289                         let team2_mediumname = expand_mediumname_if_single_team(team2, team_expansions);
290                         let row = ultimateconfig['playoff_games_start_row'] + game[3];
291                         let cols = ultimateconfig['playoff_games_cols'][game[2]];
292                         let cell_team1 = "Results!" + String.fromCharCode(cols[0] + 65) + row;
293                         let cell_score1 = "Results!" + String.fromCharCode(cols[1] + 65) + row;
294                         let cell_score2 = "Results!" + String.fromCharCode(cols[2] + 65) + row;
295                         let cell_team2 = "Results!" + String.fromCharCode(cols[3] + 65) + row;
296                         updates.push({ "range": cell_team1, "values": [ [ team1_mediumname ] ] });
297                         updates.push({ "range": cell_team2, "values": [ [ team2_mediumname ] ] });
298
299                         let score1 = response['values'][row - 1][cols[1]];
300                         let score2 = response['values'][row - 1][cols[2]];
301                         let game_name = game[4];
302                         let game_name2 = game_name.replace("Semi", "semi");
303
304                         let range = {
305                                 "sheetId": ultimateconfig['score_sheet_index'],
306                                 "startColumnIndex": cols[1],
307                                 "endColumnIndex": cols[2] + 1,
308                                 "startRowIndex": row - 1,
309                                 "endRowIndex": row
310                         };
311
312                         if (parseInt(score1) >= 0 && parseInt(score2) >= 0 && score1 != score2) {
313                                 if (parseInt(score1) > parseInt(score2)) {
314                                         replacements.unshift(["W " + game_name, team1]);
315                                         replacements.unshift(["L " + game_name, team2]);
316                                         replacements.unshift(["W " + game_name2, team1]);
317                                         replacements.unshift(["L " + game_name2, team2]);
318                                 } else {
319                                         replacements.unshift(["W " + game_name, team2]);
320                                         replacements.unshift(["L " + game_name, team1]);
321                                         replacements.unshift(["W " + game_name2, team2]);
322                                         replacements.unshift(["L " + game_name2, team1]);
323                                 }
324                                 meta_updates.push({ "unmergeCells": { "range": range }});
325                         } else if (game[5]) {
326                                 // No score yet, so write the name of the game (e.g. “L-semi 1”)
327                                 // where the score would normally be, to mark what this game is called.
328                                 // This is useful with the limited space on the tablet.
329                                 score1 = score2 = "";
330                                 updates.push({ "range": cell_score1, "values": [ [ game[4] ] ] });
331                                 meta_updates.push({ "mergeCells": { "range": range, "mergeType": "MERGE_ALL" }});
332                         }
333
334                         if (game[2] == 0) {  // Stream field.
335                                 // Game.
336                                 updates.push({
337                                         "range": "Playoffs!A" + (game_num + 32) + ":J" + (game_num + 32),
338                                         "values": [ [ team1, team2, score1, score2, "", "", "", 7, response['values'][row - 1][1].replace(".",":"), game[6] ] ]
339                                 });
340
341                                 // Team codes.
342                                 updates.push({
343                                         "range": "Playoffs!A" + (2 * game_num + 3) + ":C" + (2 * game_num + 3),
344                                         "values": [ names_for_team(team1, team_expansions) ]
345                                 });
346                                 updates.push({
347                                         "range": "Playoffs!A" + (2 * game_num + 4) + ":C" + (2 * game_num + 4),
348                                         "values": [ names_for_team(team2, team_expansions) ]
349                                 });
350
351                                 ++game_num;
352                         }
353                 }
354                 let json = {
355                         "valueInputOption": "USER_ENTERED",
356                         "data": updates 
357                 };
358                 let meta_json = {
359                         "requests": meta_updates
360                 };
361                 possibly_update_oauth_key(function() {
362                         post_json('https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values:batchUpdate?key=' + ultimateconfig['api_key'], json, function(response) {}, current_oauth_access_token);
363                         post_json('https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + ':batchUpdate?key=' + ultimateconfig['api_key'], meta_json, function(response) {}, current_oauth_access_token);
364                 });
365         });
366 }
367
368 function get_results(sheet_name, cb)
369 {
370         let req = new XMLHttpRequest();
371         req.onload = function(e) {
372                 cb(JSON.parse(req.responseText), sheet_name);
373         };
374         req.open('GET', 'https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values/\'' + sheet_name + '\'!A1:Q50?key=' + ultimateconfig['api_key']);
375         req.send();
376 }
377
378 function publish_group_ranks() {
379         get_group('Group A', function(response_a) {
380                 get_group('Group B', function(response_b) {
381                         get_group('Group C', function(response_c) {
382                                 publish_group_rank(response_a, 'Group A');
383                                 publish_group_rank(response_b, 'Group B');
384                                 publish_group_rank(response_c, 'Group C');
385
386                                 let replacements = montecarlo([response_a, response_b, response_c]);
387                                 let team_a = parse_teams_from_spreadsheet(response_a);
388                                 let team_b = parse_teams_from_spreadsheet(response_b);
389                                 let team_c = parse_teams_from_spreadsheet(response_c);
390                                 fill_playoff(replacements, [team_a, team_b, team_c]);
391                         });
392                 });
393         });
394 }
395
396 function get_ranked(response, group_name) {
397         let teams = parse_teams_from_spreadsheet(response);
398         let games = parse_games_from_spreadsheet(response, group_name, false);
399         apply_games_to_teams(games, teams);
400         let tiebreakers = [];
401         teams = rank(games, teams, 1, tiebreakers);
402         return teams;
403 }
404
405 // Pick out everything that is at rank N _or_ avoids rank N by lack of tiebreakers only.
406 function pick_out_rank(teams, rank, candidates) {
407         let lowest_rank = teams[rank - 1].rank;
408
409         let count = 0;
410         for (const team of teams) {
411                 if (team.rank >= lowest_rank && team.rank <= rank) {
412                         ++count;
413                 }
414         }
415
416         if (count >= teams.length / 2) {
417                 // We have no info yet, ignore this group.
418                 return;
419         }
420
421         for (const team of teams) {
422                 if (team.rank >= lowest_rank && team.rank <= rank) {
423                         candidates.push(team);
424                 }
425         }
426 }
427
428 function publish_best_thirds() {
429         get_group('Group A', function(response_a) {
430                 get_group('Group B', function(response_b) {
431                         get_group('Group C', function(response_c) {
432                                 let A = get_ranked(response_a, 'Group A');
433                                 let B = get_ranked(response_b, 'Group B');
434                                 let C = get_ranked(response_c, 'Group C');
435
436                                 let candidates = [];
437                                 pick_out_rank(A, 3, candidates);
438                                 pick_out_rank(B, 3, candidates);
439                                 pick_out_rank(C, 3, candidates);
440
441                                 let tiebreakers = [];
442                                 let text = "";
443                                 if (candidates.length >= 2) {
444                                         let ranked = rank_thirds([], candidates, 1, tiebreakers);
445                                         text = "Best thirds: " + ranked[0].mediumname + ", " + ranked[1].mediumname + "\n" + tiebreakers.join("\n");
446                                 }
447                                 let updates = [];
448                                 updates.push({ "range": ultimateconfig['explain_third_cell'], "values": [ [ text ] ] });
449                                 let json = {
450                                         "valueInputOption": "USER_ENTERED",
451                                         "data": updates 
452                                 };
453                                 possibly_update_oauth_key(function() {
454                                         post_json('https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values:batchUpdate?key=' + ultimateconfig['api_key'], json, function(response) {}, current_oauth_access_token);
455                                 });
456                         });
457                 });
458         });
459 }
460
461 update_oauth_key();
462 setTimeout(function() {
463         publish_group_ranks();
464         publish_best_thirds();
465         setInterval(function() { publish_group_ranks(); publish_best_thirds(); }, 60000);
466 }, 5000);