]> git.sesse.net Git - ultimatescore/blob - update_sheets.js
Fix an issue where newer browsers would squeeze the secondary scorebugs.
[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         teams = filter_teams(teams, response);
78
79         // Write the points total to the unsorted columns.
80         if (config['point_total_start_row'] !== null) {
81                 for (let i = 0; i < teams.length; ++i) {
82                         let row = config['point_total_start_row'] + i;
83                         updates.push({ "range": cols[2] + row, "values": [ [ teams[i].pts ] ] });
84                 }
85         }
86
87         let tiebreakers = [];
88         teams = rank(games, teams, 1, tiebreakers);
89
90         // Write the ranking table, from scratch.
91         for (let i = 0; i < teams.length; ++i) {
92                 let row = config['ranking_list_start_row'] + i;
93                 updates.push({ "range": cols[0] + row, "values": [ [ teams[i].rank + config['rank_offset'] - 1] ] });
94                 updates.push({ "range": cols[1] + row, "values": [ [ teams[i].mediumname ] ] });
95                 updates.push({ "range": cols[2] + row, "values": [ [ teams[i].pts ] ] });
96         }
97
98         let tb_str = "";
99         if (tiebreakers.length != 0) {
100                 tb_str = tiebreakers.join("\n");
101         }
102         updates.push({ "range": config['ranking_list_explain_cell'], "values": [ [ tb_str ] ]});
103
104         let json = {
105                 "valueInputOption": "USER_ENTERED",
106                 "data": updates 
107         };
108         possibly_update_oauth_key(function() {
109                 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);
110         });
111 }
112
113 function montecarlo(responses) {
114         let pseudo_group_names = ['X', 'Y', 'Z'];
115         let real_group_names = ['A', 'B', 'C'];
116         let teams = [], games = [], teams_to_idx = [];
117
118         let third_groups = [];
119         let busted_thirds = false;
120
121         for (const response of responses) {
122                 let teams_group = parse_teams_from_spreadsheet(response);
123                 let games_group = parse_games_from_spreadsheet(response, 'irrelevant group name', true);
124                 apply_games_to_teams(games_group, teams_group);
125
126                 teams.push(teams_group);
127                 games.push(games_group);
128                 teams_to_idx.push(make_teams_to_idx(teams_group));
129         }
130
131         for (let simulation_idx = 0; simulation_idx < 100; ++simulation_idx) {  // 100 seems to be enough.
132                 let thirds = [], ignoreds = [];
133                 let groups = [];
134                 for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
135                         // Fill in random results. We deliberately use a uniform [-13,+13]
136                         // model here, since we are interested in the extremal results.
137                         // Of course, not all real games go to 13, but the risk of that
138                         // influencing the tiebreakers is very slim.
139                         let games_copy = [], games_with_synth = [];
140                         for (const game of games[group_idx]) {
141                                 games_copy.push(Object.assign({}, game));
142                         }
143                         let teams_copy = [];
144                         for (const team of teams[group_idx]) {
145                                 teams_copy.push(Object.assign({}, team));
146                         }
147
148                         for (let i = 0; i < games_copy.length; ++i) {
149                                 let idx1 = teams_to_idx[group_idx][games_copy[i].name1];
150                                 let idx2 = teams_to_idx[group_idx][games_copy[i].name2];
151                                 if (idx1 === undefined || idx2 === undefined) continue;
152                                 if (games_copy[i].score1 === undefined || games_copy[i].score2 === undefined ||
153                                     isNaN(games_copy[i].score1) || isNaN(games_copy[i].score2) ||
154                                     games_copy[i].score1 == games_copy[i].score2) {
155                                         // These were skipped by apply_games_to_teams() above.
156                                         let score1 = 0, score2 = 0;
157                                         let r = Math.floor(Math.random() * 26);
158                                         if (r < 13) {
159                                                 score1 = 13;
160                                                 score2 = r;
161                                                 teams_copy[idx1].pts += 2;
162                                         } else {
163                                                 score1 = r - 13;
164                                                 score2 = 13;
165                                                 teams_copy[idx2].pts += 2;
166                                         }
167                                         games_copy[i].score1 = score1;
168                                         games_copy[i].score2 = score2;
169                                         ++teams_copy[idx1].nplayed;
170                                         ++teams_copy[idx2].nplayed;
171                                         teams_copy[idx1].goals += score1;
172                                         teams_copy[idx2].goals += score2;
173                                         teams_copy[idx1].gd += score1;
174                                         teams_copy[idx2].gd += score2;
175                                         teams_copy[idx1].gd -= score2;
176                                         teams_copy[idx2].gd -= score1;
177
178                                         games_with_synth.push({
179                                                 "name1": games_copy[i].name1,
180                                                 "name2": games_copy[i].name2,
181                                                 "score1": score1,
182                                                 "score2": score2
183                                         });
184                                 } else {
185                                         games_with_synth.push(games_copy[i]);
186                                         continue;
187                                 }
188                         }
189                         
190                         // Now rank according to the simulation.
191                         let tiebreakers = [];
192                         teams_copy = rank(games_copy, teams_copy, 1, tiebreakers);
193
194                         // See if we have conflicting information with other simulations.
195                         if (simulation_idx == 0) {
196                                 for (let i = 0; i < teams[group_idx].length; ++i) {
197                                         let idx = teams_to_idx[group_idx][teams_copy[i].name];
198                                         teams[group_idx][idx].simulated_rank = teams_copy[i].rank;
199                                 }
200                         } else {
201                                 for (let i = 0; i < teams[group_idx].length; ++i) {
202                                         let idx = teams_to_idx[group_idx][teams_copy[i].name];
203                                         if (teams[group_idx][idx].simulated_rank !== teams_copy[i].rank) {
204                                                 teams[group_idx][idx].simulated_rank = null;
205                                         }
206                                 }
207                         }
208
209                         if (!busted_thirds) {
210                                 let any_third_found = false;
211                                 for (let i = 0; i < teams[group_idx].length; ++i) {
212                                         // Store the third.
213                                         if (i == 2 || teams_copy[i].rank == 3) {
214                                                 if (any_third_found) {
215                                                         busted_thirds = true;
216                                                 } else {
217                                                         teams_copy[i].group_idx = group_idx;
218                                                         thirds.push(teams_copy[i]);
219                                                         any_third_found = true;
220                                                 }
221                                         }
222                                 }
223                                 if (ultimateconfig['kick_fifth_from_third'] && teams_copy.length >= 5) {
224                                         if (teams_copy[4].rank != 5) {
225                                                 // A real tie for fifth; the rules are unclear, so just give up.
226                                                 busted_thirds = true;
227                                         } else {
228                                                 ignoreds.push(teams_copy[4]);
229                                         }
230                                 }
231                         }
232
233                         groups.push({
234                                 "games": games_with_synth,
235                                 "teams": teams_copy
236                         });
237                 }
238
239                 // Also rank thirds.
240                 if (!busted_thirds) {
241                         let tiebreakers = [];
242                         if (ultimateconfig['kick_fifth_from_third']) {
243                                 // Recompute scores (but not ranks!) without the ignored games. (thirds point to these objects.)
244                                 for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
245                                         apply_games_to_teams(groups[group_idx].games, groups[group_idx].teams, ignoreds);
246                                 }
247                         }
248                         let ranked = rank_thirds([], thirds, 1, tiebreakers);
249                         if (simulation_idx == 0) {
250                                 third_groups = ranked;
251                         } else {
252                                 for (let i = 0; i < responses.length; ++i) {
253                                         if (third_groups[i].group_idx !== ranked[i].group_idx) {
254                                                 third_groups[i].group_idx = null;
255                                         }
256                                 }
257                         }
258                 }
259         }
260
261         let replacements = [];
262         for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
263                 if (third_groups[group_idx].group_idx !== null) {
264                         replacements.push([ pseudo_group_names[group_idx], real_group_names[third_groups[group_idx].group_idx] ]);
265                 }
266         }
267
268         for (let group_idx = 0; group_idx < responses.length; ++group_idx) {
269                 for (let i = 0; i < teams[group_idx].length; ++i) {
270                         if (teams[group_idx][i].simulated_rank !== null) {
271                                 replacements.push([ real_group_names[group_idx] + teams[group_idx][i].simulated_rank, teams[group_idx][i].shortname ]);
272                         }
273                 }
274         }
275
276         return replacements;
277 }
278
279 function names_for_team(team, expansions) {
280         if (expansions.hasOwnProperty(team)) {
281                 return expansions[team];
282         }
283         let longteam = team.replace("W ", "Win. ").replace("L ", "Los. ");
284         return [ longteam, longteam, team ];
285 }
286
287 function expand_mediumname_if_single_team(team, expansions) {
288         if (expansions.hasOwnProperty(team)) {
289                 return expansions[team][1];
290         }
291         return team;
292 }
293
294 function do_replacements(str, replacements) {
295         for (const r of replacements) {
296                 str = str.replace(r[0], r[1]);
297         }
298         return str;
299 }
300
301 function fill_playoff(replacements, teams) {
302         let team_expansions = {};
303         for (const group of teams) {
304                 for (const team of group) {
305                         team_expansions[team.name] = team_expansions[team.mediumname] = team_expansions[team.shortname] =
306                                 [ team.name, team.mediumname, team.shortname ];
307                 }
308         }
309
310         let games = ultimateconfig['playoff_games'];
311         get_results('Results', function(response) {
312                 let updates = [], meta_updates = [];
313                 let game_num = 0;
314                 for (const game of games) {
315                         let team1 = do_replacements(game[0], replacements);
316                         let team2 = do_replacements(game[1], replacements);
317                         let team1_mediumname = expand_mediumname_if_single_team(team1, team_expansions);
318                         let team2_mediumname = expand_mediumname_if_single_team(team2, team_expansions);
319                         let row = ultimateconfig['playoff_games_start_row'] + game[3];
320                         let cols = ultimateconfig['playoff_games_cols'][game[2]];
321                         let cell_team1 = "Results!" + String.fromCharCode(cols[0] + 65) + row;
322                         let cell_score1 = "Results!" + String.fromCharCode(cols[1] + 65) + row;
323                         let cell_score2 = "Results!" + String.fromCharCode(cols[2] + 65) + row;
324                         let cell_team2 = "Results!" + String.fromCharCode(cols[3] + 65) + row;
325                         updates.push({ "range": cell_team1, "values": [ [ team1_mediumname ] ] });
326                         updates.push({ "range": cell_team2, "values": [ [ team2_mediumname ] ] });
327
328                         let score1 = response['values'][row - 1][cols[1]];
329                         let score2 = response['values'][row - 1][cols[2]];
330                         let game_name = game[4];
331                         let game_name2 = game_name.replace("Semi", "semi");
332                         let game_day = game[7];
333                         if (game_day === undefined) {
334                                 game_day = 7;  // Sunday.
335                         }
336
337                         let range = {
338                                 "sheetId": ultimateconfig['score_sheet_index'],
339                                 "startColumnIndex": cols[1],
340                                 "endColumnIndex": cols[2] + 1,
341                                 "startRowIndex": row - 1,
342                                 "endRowIndex": row
343                         };
344
345                         if (parseInt(score1) >= 0 && parseInt(score2) >= 0 && score1 != score2) {
346                                 if (parseInt(score1) > parseInt(score2)) {
347                                         replacements.unshift(["W " + game_name, team1]);
348                                         replacements.unshift(["L " + game_name, team2]);
349                                         replacements.unshift(["W " + game_name2, team1]);
350                                         replacements.unshift(["L " + game_name2, team2]);
351                                 } else {
352                                         replacements.unshift(["W " + game_name, team2]);
353                                         replacements.unshift(["L " + game_name, team1]);
354                                         replacements.unshift(["W " + game_name2, team2]);
355                                         replacements.unshift(["L " + game_name2, team1]);
356                                 }
357                                 meta_updates.push({ "unmergeCells": { "range": range }});
358                         } else if (game[5]) {
359                                 // No score yet, so write the name of the game (e.g. “L-semi 1”)
360                                 // where the score would normally be, to mark what this game is called.
361                                 // This is useful with the limited space on the tablet.
362                                 score1 = score2 = "";
363                                 updates.push({ "range": cell_score1, "values": [ [ game[4] ] ] });
364                                 meta_updates.push({ "mergeCells": { "range": range, "mergeType": "MERGE_ALL" }});
365                         }
366
367                         if (game[2] == 0) {  // Stream field.
368                                 // Game.
369                                 let ss_row = ultimateconfig['playoff_games_start_row_detail_sheet'] + game_num;
370                                 updates.push({
371                                         "range": "Playoffs!A" + ss_row + ":J" + ss_row,
372                                         "values": [ [ team1, team2, score1, score2, "", "", "", game_day, response['values'][row - 1][1].replace(".",":"), game[6] ] ]
373                                 });
374
375                                 // Team codes.
376                                 updates.push({
377                                         "range": "Playoffs!A" + (2 * game_num + 3) + ":C" + (2 * game_num + 3),
378                                         "values": [ names_for_team(team1, team_expansions) ]
379                                 });
380                                 updates.push({
381                                         "range": "Playoffs!A" + (2 * game_num + 4) + ":C" + (2 * game_num + 4),
382                                         "values": [ names_for_team(team2, team_expansions) ]
383                                 });
384
385                                 ++game_num;
386                         }
387                 }
388                 let json = {
389                         "valueInputOption": "USER_ENTERED",
390                         "data": updates 
391                 };
392                 let meta_json = {
393                         "requests": meta_updates
394                 };
395                 possibly_update_oauth_key(function() {
396                         post_json('https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values:batchUpdate?key=' + ultimateconfig['api_key'], json, function(response) {
397                         }, current_oauth_access_token);
398                         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);
399                 });
400         });
401 }
402
403 function get_results(sheet_name, cb)
404 {
405         let req = new XMLHttpRequest();
406         req.onload = function(e) {
407                 cb(JSON.parse(req.responseText), sheet_name);
408         };
409         req.open('GET', 'https://sheets.googleapis.com/v4/spreadsheets/' + ultimateconfig['score_sheet_id'] + '/values/\'' + sheet_name + '\'!A1:Q50?key=' + ultimateconfig['api_key']);
410         req.send();
411 }
412
413 function publish_group_ranks() {
414         get_group('Group A', function(response_a) {
415                 get_group('Group B', function(response_b) {
416                                 publish_group_rank(response_a, 'Group A');
417                                 publish_group_rank(response_b, 'Group B');
418
419                                 let replacements = montecarlo([response_a, response_b]);
420                                 let team_a = parse_teams_from_spreadsheet(response_a);
421                                 let team_b = parse_teams_from_spreadsheet(response_b);
422                                 fill_playoff(replacements, [team_a, team_b]);
423                 });
424         });
425 }
426
427 function get_ranked(response, group_name) {
428         let teams = parse_teams_from_spreadsheet(response);
429         let games = parse_games_from_spreadsheet(response, group_name, false);
430         apply_games_to_teams(games, teams);
431         teams = filter_teams(teams, response);
432         let tiebreakers = [];
433         teams = rank(games, teams, 1, tiebreakers);
434         return teams;
435 }
436
437 // Pick out everything that is at rank N _or_ avoids rank N by lack of tiebreakers only.
438 function pick_out_rank(teams, rank, candidates) {
439         if (teams.length < rank) {
440                 return;
441         }
442
443         let lowest_rank = teams[rank - 1].rank;
444
445         let count = 0;
446         for (const team of teams) {
447                 if (team.rank >= lowest_rank && team.rank <= rank) {
448                         ++count;
449                 }
450         }
451
452         if (count >= teams.length / 2) {
453                 // We have no info yet, ignore this group.
454                 return;
455         }
456
457         for (const team of teams) {
458                 if (team.rank >= lowest_rank && team.rank <= rank) {
459                         candidates.push(team);
460                 }
461         }
462 }
463
464 function addsign(x)
465 {
466         if (x < 0) {
467                 return "−" + (-x);
468         } else if (x == 0) {
469                 return "=0";
470         } else {
471                 return "+" + x;
472         }
473 }
474
475 function publish_best_thirds() {
476         if (!ultimateconfig['best_thirds']) return;
477         get_group('Group A', function(response_a) {
478                 get_group('Group B', function(response_b) {
479                         get_group('Group C', function(response_c) {
480                                 let A = get_ranked(response_a, 'Group A');
481                                 let B = get_ranked(response_b, 'Group B');
482                                 let C = get_ranked(response_c, 'Group C');
483
484                                 let candidates = [];
485                                 pick_out_rank(A, 3, candidates);
486                                 pick_out_rank(B, 3, candidates);
487                                 pick_out_rank(C, 3, candidates);
488
489                                 let ignoreds = [];
490                                 let ignored_games = [], ignored_games_expl = [];
491                                 if (ultimateconfig['kick_fifth_from_third']) {
492                                         let ignoreds_A = [], ignoreds_B = [], ignoreds_C = [];
493                                         pick_out_rank(A, 5, ignoreds_A);
494                                         pick_out_rank(B, 5, ignoreds_B);
495                                         pick_out_rank(C, 5, ignoreds_C);
496
497                                         if (ignoreds_A.length >= 2) {
498                                                 ignoreds_A = [ ignoreds_A[ignoreds_A.length - 1] ];
499                                         }
500                                         if (ignoreds_B.length >= 2) {
501                                                 ignoreds_B = [ ignoreds_B[ignoreds_B.length - 1] ];
502                                         }
503                                         if (ignoreds_C.length >= 2) {
504                                                 ignoreds_C = [ ignoreds_C[ignoreds_C.length - 1] ];
505                                         }
506                                         ignoreds = ignoreds_A.concat(ignoreds_B).concat(ignoreds_C);
507
508                                         // Protect the “candidates” array, so that apply_games_to_teams() further down
509                                         // doesn't modify it (we want to compare old and new).
510                                         A = jsonclone(A);
511                                         B = jsonclone(B);
512                                         C = jsonclone(C);
513
514                                         // Recompute scores (but not ranks!) without the ignored games.
515                                         let games_a = parse_games_from_spreadsheet(response_a, 'Group A', false);
516                                         apply_games_to_teams(games_a, A, ignoreds, ignored_games);
517                                         let games_b = parse_games_from_spreadsheet(response_b, 'Group B', false);
518                                         apply_games_to_teams(games_b, B, ignoreds, ignored_games);
519                                         let games_c = parse_games_from_spreadsheet(response_c, 'Group C', false);
520                                         apply_games_to_teams(games_c, C, ignoreds, ignored_games);
521
522                                         // Filter out ignored games involving the candidate thirds.
523                                         let candidates_to_idx = make_teams_to_idx(candidates);
524                                         for (const game of ignored_games) {
525                                                 if (candidates_to_idx[game[0]] !== undefined ||
526                                                     candidates_to_idx[game[1]] !== undefined) {
527                                                         if (game[2]) {
528                                                                 ignored_games_expl.push("Ignoring (arbitrarily) " + game[0] + "–" + game[1]);
529                                                         } else {
530                                                                 ignored_games_expl.push("Ignoring " + game[0] + "–" + game[1]);
531                                                         }
532                                                 }
533                                         }
534
535                                         let new_teams = A.concat(B).concat(C);
536                                         let new_teams_to_idx = make_teams_to_idx(new_teams);
537
538                                         // Move back the scores (points, gd, goals).
539                                         for (let cand of candidates) {
540                                                 let new_version = new_teams[new_teams_to_idx[cand.shortname]];
541                                                 if (cand.pts != new_version.pts ||
542                                                     cand.gd != new_version.gd ||
543                                                     cand.goals != new_version.goals) {
544                                                         cand.pts = new_version.pts;
545                                                         cand.gd = new_version.gd;
546                                                         cand.goals = new_version.goals;
547                                                         ignored_games_expl.push(cand.shortname + " at " + cand.pts + " pts, " + addsign(new_version.gd) + " GD");
548                                                 }
549                                         }
550                                 }
551
552                                 let tiebreakers = [];
553                                 let text = "";
554                                 if (candidates.length >= 2) {
555                                         let ranked = rank_thirds([], candidates, 1, tiebreakers);
556                                         let best_thirds = ranked.filter(function(team) { return team.rank <= 2; });
557                                         if (best_thirds.length == 2) {
558                                                 text = "Best thirds: " + best_thirds.map(function(team) { return team.mediumname }).join(', ') + "\n";
559                                                 if (ignored_games_expl.length > 0) {
560                                                         text += ignored_games_expl.join("; ") + "\n";
561                                                 }
562                                                 text += tiebreakers.join("\n");
563                                         }
564                                 }
565                                 let updates = [];
566                                 updates.push({ "range": ultimateconfig['explain_third_cell'], "values": [ [ text ] ] });
567                                 let json = {
568                                         "valueInputOption": "USER_ENTERED",
569                                         "data": updates 
570                                 };
571                                 possibly_update_oauth_key(function() {
572                                         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);
573                                 });
574                         });
575                 });
576         });
577 }
578
579 update_oauth_key();
580 setTimeout(function() {
581         publish_group_ranks();
582         publish_best_thirds();
583         setInterval(function() { publish_group_ranks(); publish_best_thirds(); }, 60000);
584 }, 5000);