/** * Live Tennis API for Google Sheets, version 1.0 * https://livetennisapi.com/integrations/google-sheets * * Custom functions: * =TENNIS_LIVE(tour, refresh) matches being played now, with the score * =TENNIS_UPCOMING(date, tour, refresh) matches of one day still to start * =TENNIS_PLAYERS(name, limit) players whose name matches * * Sheets runs a custom function again only when an argument changes. Point refresh at a * checkbox and tick it to ask for new data. * * Setup: reload the spreadsheet, open the Live Tennis API menu and choose Set API key. * The key is kept in this project's Script Properties, never in a cell. * * API reference: https://docs.livetennisapi.com/ * * @OnlyCurrentDoc * * MIT License * * Copyright (c) 2026 JSB Holdings LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var LTAPI_VERSION = '1.0'; var LTAPI_BASE_URL = 'https://api.livetennisapi.com/api/public/v1'; var LTAPI_KEY_PROPERTY = 'LIVETENNISAPI_KEY'; var LTAPI_LIMITS_PROPERTY = 'LIVETENNISAPI_LIMITS'; var LTAPI_LOG_PROPERTY = 'LIVETENNISAPI_REQUEST_LOG'; var LTAPI_BLOCK_PROPERTY = 'LIVETENNISAPI_WAIT'; // The free plan allows 30 requests a minute and 100 a day, as the docs state at // https://docs.livetennisapi.com/errors-and-rate-limits.html // The script holds itself to the minute limit. The API keeps count of the day. // Check my key replaces these with your own plan's limits. var LTAPI_FREE_LIMITS = { perMinute: 30, perDay: 100 }; // How long each answer is kept before the API is asked again, in seconds. Apps Script can // drop a saved answer sooner, so these are the longest times, not promises. // On a paid plan you can lower the live figure. CacheService keeps at most 21600. var LTAPI_CACHE_SECONDS = { live: 900, upcoming: 3600, players: 21600 }; var LTAPI_TOURS = ['atp', 'wta', 'challenger', 'itf', 'juniors']; var LTAPI_PAGE_SIZE = 200; // the largest page the API serves var LTAPI_MAX_PAGES = 3; // a busy day is fetched in up to three pages var LTAPI_PAGE_OVERLAP = 20; // rows each page repeats, in case the list moved meanwhile var LTAPI_LOCK_WAIT = 5000; // milliseconds a cell waits for another cell to finish var LTAPI_TIME_BUDGET = 10000; // no new page after this, inside Sheets' 30 seconds var LTAPI_LOG_MAX = 300; // request times kept for the minute check var LTAPI_CHUNK = 30000; // characters per cache entry, under the 100 KB cap var LTAPI_HEADERS = { live: ['Tournament', 'Tour', 'Round', 'Player 1', 'Player 2', 'Sets', 'Games', 'Points', 'Serving', 'Tiebreak', 'Live since', 'Match ID'], upcoming: ['Start', 'Tournament', 'Tour', 'Round', 'Player 1', 'Player 2', 'Surface', 'Format', 'Note', 'Match ID'], players: ['Player ID', 'Name', 'Tour', 'Country', 'Ranking', 'Ranking points', 'Movement', 'Ranking status', 'Hand', 'Birthday'] }; // Columns that hold a time. They are cached as text and become dates on the way out. var LTAPI_DATE_COLUMNS = { live: [10], upcoming: [0], players: [] }; /** * Tennis matches being played now, one row each, with the score. * * @param {string} tour Optional. atp, wta, challenger, itf or juniors. Leave it out for every tour. * @param {boolean} refresh Optional. A cell, for example a checkbox. Sheets runs the function again when it changes. * @return A header row, then one row per live match. * @customfunction */ function TENNIS_LIVE(tour, refresh) { var query = { status: 'live' }; var t = ltapiTour_(tour); if (t) query.tour = t; var result = ltapiList_('/matches', query, LTAPI_CACHE_SECONDS.live, ltapiLiveRow_); return ltapiTable_('live', result, 'No live matches right now.', !!t); } /** * Tennis matches of one day that have not started yet, earliest first. * * @param {string} date Optional. A date cell, DATE(2026,11,24) or "2026-11-24". Leave it out for today. The day runs midnight to midnight in the spreadsheet's time zone. * @param {string} tour Optional. atp, wta, challenger, itf or juniors. Leave it out for every tour. * @param {boolean} refresh Optional. A cell, for example a checkbox. Sheets runs the function again when it changes. * @return A header row, then one row per match. * @customfunction */ function TENNIS_UPCOMING(date, tour, refresh) { var day = ltapiDay_(date); var query = { status: 'upcoming', from: day.from, to: day.to }; var t = ltapiTour_(tour); if (t) query.tour = t; var result = ltapiList_('/matches', query, LTAPI_CACHE_SECONDS.upcoming, ltapiUpcomingRow_); result.rows.sort(function (a, b) { var x = a[0] ? Date.parse(a[0]) : NaN; var y = b[0] ? Date.parse(b[0]) : NaN; if (isNaN(x) && isNaN(y)) return 0; if (isNaN(x)) return 1; if (isNaN(y)) return -1; return x - y; }); return ltapiTable_('upcoming', result, 'No matches still to start on ' + day.label + '.', !!t); } /** * Tennis players whose name matches, ranked players first. * * @param {string} name Part of a player's name, for example "Sinner". * @param {number} limit Optional. How many players to list, 1 to 50. The default is 10. * @return A header row, then one row per player. * @customfunction */ function TENNIS_PLAYERS(name, limit) { var search = String(name === undefined || name === null ? '' : name).trim(); if (!search) { throw new Error('Give part of a player\'s name, for example =TENNIS_PLAYERS("Sinner").'); } var n = 10; if (limit !== undefined && limit !== null && limit !== '') { n = typeof limit === 'number' ? limit : typeof limit === 'string' ? Number(limit.trim()) : NaN; } if (!(n >= 1 && n <= 50) || Math.floor(n) !== n) { throw new Error('The limit must be a whole number from 1 to 50.'); } var query = { search: search, limit: n }; var result = ltapiList_('/players', query, LTAPI_CACHE_SECONDS.players, ltapiPlayerRow_, 1); result.more = false; return ltapiTable_('players', result, 'No player found for "' + search + '".', false); } /** Adds the Live Tennis API menu when the spreadsheet opens. */ function onOpen() { ltapiAddMenu(); } /** The menu itself. If your project has its own onOpen, delete the one above and call this. */ function ltapiAddMenu() { SpreadsheetApp.getUi().createMenu('Live Tennis API') .addItem('Set API key', 'ltapiSetKey') .addItem('Check my key', 'ltapiCheckKey') .addItem('Remove API key', 'ltapiRemoveKey') .addToUi(); } /** The one-time setup: asks for the key and saves it in Script Properties. */ function ltapiSetKey() { var ui = SpreadsheetApp.getUi(); var answer = ui.prompt('Live Tennis API key', 'Paste your API key. It is saved in this script\'s properties, not in the sheet.', ui.ButtonSet.OK_CANCEL); if (answer.getSelectedButton() !== ui.Button.OK) return; var key = answer.getResponseText().trim(); if (!key) { ui.alert('No key was entered, so nothing changed.'); return; } // The new key is checked before it is saved, so a key that fails never replaces one that // works. The request log and any wait stay with the key they belong to. var usage = ltapiUsage_(key); if (usage.error) { ui.alert(usage.error + '\nThe saved key was not changed.'); return; } var props = PropertiesService.getScriptProperties(); props.setProperty(LTAPI_KEY_PROPERTY, key); ui.alert(ltapiUsageText_(usage.body, key)); } /** Asks the API which plan the key is on and how much of today's allowance is left. */ function ltapiCheckKey() { var ui = SpreadsheetApp.getUi(); var key; try { key = ltapiKey_(); } catch (e) { ui.alert(e.message); return; } var usage = ltapiUsage_(key); ui.alert(usage.error || ltapiUsageText_(usage.body, key)); } /** Deletes the key, the saved plan limits, the request log and any wait. */ function ltapiRemoveKey() { // The dialog comes first. A cell that calls this by name stops here, before it can // delete anything, because a custom function cannot open a dialog. var ui = SpreadsheetApp.getUi(); var props = PropertiesService.getScriptProperties(); props.deleteProperty(LTAPI_KEY_PROPERTY); props.deleteProperty(LTAPI_LIMITS_PROPERTY); props.deleteProperty(LTAPI_LOG_PROPERTY); props.deleteProperty(LTAPI_BLOCK_PROPERTY); ui.alert('The API key was removed from this spreadsheet\'s script.'); } // GET /usage for one key, which the API does not count. The script lock keeps it from // running alongside a cell, so a wait it writes cannot cross one a cell writes. The result // is {body} or {error}. The plan limits it reports are saved for that key alone. function ltapiUsage_(key) { var lock = LockService.getScriptLock(); if (!lock.tryLock(LTAPI_LOCK_WAIT)) { return { error: 'Cells are loading Live Tennis API data. Try again in a moment.' }; } try { var body; try { body = ltapiFetch_('/usage', {}, false, key); } catch (e) { return { error: e.message }; } if (!body || typeof body !== 'object') { return { error: 'Live Tennis API sent an answer this script cannot read. Try again later.' }; } var hash = ltapiHash_(key); var limits = body.limits || {}; PropertiesService.getScriptProperties().setProperty(LTAPI_LIMITS_PROPERTY, JSON.stringify({ k: hash, perMinute: typeof limits.per_minute === 'number' ? limits.per_minute : null, perDay: typeof limits.per_day === 'number' ? limits.per_day : null })); var today = body.today || {}; if (typeof today.remaining_day === 'number' && today.remaining_day > 0) { // The API says requests are left today, so a wait saved after a daily 429 is over. ltapiWaitClear_(hash, 'day'); } return { body: body }; } finally { lock.releaseLock(); } } function ltapiUsageText_(usage, key) { var limits = ltapiLimits_(ltapiHash_(key)); var today = usage.today || {}; var lines = ['The key works. Plan: ' + String(usage.tier || 'unknown').toUpperCase() + '.']; if (typeof limits.perMinute === 'number') lines.push('Requests a minute: ' + limits.perMinute + '.'); if (typeof limits.perDay === 'number') lines.push('Requests a day: ' + limits.perDay + '.'); if (typeof today.remaining_day === 'number') { lines.push('Left today: ' + today.remaining_day + '.'); } return lines.join('\n'); } // Rows. Each one turns an API record into plain cells. Missing values become empty cells. function ltapiLiveRow_(m) { var p = m.players || {}; var s = m.score || {}; var p1 = ltapiName_(p.p1); var p2 = ltapiName_(p.p2); var server = s.server === 1 ? p1 : s.server === 2 ? p2 : ''; return [ltapiCell_(m.tournament), ltapiCell_(m.tour), ltapiCell_(m.round), p1, p2, ltapiPair_(s.sets), ltapiGames_(s.games), ltapiPair_(s.points), server, s.is_tiebreak === true ? 'Yes' : s.is_tiebreak === false ? 'No' : '', ltapiCell_(m.live_at), ltapiCell_(m.id)]; } function ltapiUpcomingRow_(m) { var p = m.players || {}; return [ltapiCell_(m.scheduled_time), ltapiCell_(m.tournament), ltapiCell_(m.tour), ltapiCell_(m.round), ltapiName_(p.p1), ltapiName_(p.p2), ltapiCell_(m.surface), ltapiCell_(m.format), ltapiCell_(m.event_status), ltapiCell_(m.id)]; } function ltapiPlayerRow_(p) { return [ltapiCell_(p.id), ltapiCell_(p.name), ltapiCell_(p.tour), ltapiCell_(p.country), ltapiCell_(p.ranking), ltapiCell_(p.ranking_points), ltapiCell_(p.ranking_movement), ltapiCell_(p.ranking_status), ltapiCell_(p.hand), ltapiCell_(p.birthday)]; } function ltapiCell_(v) { return v === undefined || v === null ? '' : v; } function ltapiName_(player) { return player && player.name ? player.name : ''; } // [1, 0] becomes "1-0". Anything else becomes an empty cell. function ltapiPair_(pair) { if (!pair || pair.length !== 2 || pair[0] === null || pair[1] === null) return ''; return pair[0] + '-' + pair[1]; } // [[6, 3, 2], [2, 6, 3]] holds each player's games by set and becomes "6-2 3-6 2-3". // Null means the score is withheld, so the cell stays empty. function ltapiGames_(games) { if (!games || games.length !== 2 || !games[0] || !games[1]) return ''; var sets = []; for (var i = 0; i < Math.max(games[0].length, games[1].length); i++) { var a = games[0][i]; var b = games[1][i]; sets.push((a === undefined || a === null ? '' : a) + '-' + (b === undefined || b === null ? '' : b)); } return sets.join(' '); } function ltapiTable_(kind, result, emptyText, filtered) { // result.error holds the message of a later page that failed, if one did. var header = LTAPI_HEADERS[kind]; var width = header.length; var dates = LTAPI_DATE_COLUMNS[kind]; var out = [header.slice()]; result.rows.forEach(function (row) { var r = row.slice(); dates.forEach(function (c) { if (r[c]) { var d = new Date(r[c]); r[c] = isNaN(d.getTime()) ? r[c] : d; } }); out.push(r); }); if (result.rows.length === 0) out.push(ltapiPad_(emptyText, width)); if (result.error) { out.push(ltapiPad_('Only part of the list was read. ' + result.error, width)); } else if (result.more) { out.push(ltapiPad_(filtered ? 'There are more rows than the script fetches.' : 'There are more rows than the script fetches. Add a tour to narrow the list.', width)); } return out; } function ltapiPad_(text, width) { var row = [text]; while (row.length < width) row.push(''); return row; } // Arguments. function ltapiTour_(tour) { var t = String(tour === undefined || tour === null ? '' : tour).trim().toLowerCase(); if (!t) return ''; if (LTAPI_TOURS.indexOf(t) === -1) { throw new Error('Unknown tour "' + tour + '". Use atp, wta, challenger, itf or juniors, or leave it out.'); } return t; } // Turns the date argument into the start and end of that day in the spreadsheet's time zone, // as UTC instants. The API's from and to both include the instant they name. function ltapiDay_(date) { var tz = ltapiTimeZone_(); var ymd; if (date === undefined || date === null || date === '') { ymd = Utilities.formatDate(new Date(), tz, 'yyyy-MM-dd'); } else if (Object.prototype.toString.call(date) === '[object Date]') { if (isNaN(date.getTime())) throw new Error('The date is not a valid date.'); ymd = Utilities.formatDate(date, tz, 'yyyy-MM-dd'); } else { ymd = String(date).trim(); } var m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(ymd); if (!m) { throw new Error('Give the date as a date cell, DATE(2026,11,24) or "2026-11-24".'); } var y = Number(m[1]); var mo = Number(m[2]) - 1; var d = Number(m[3]); var check = new Date(Date.UTC(y, mo, d)); if (check.getUTCFullYear() !== y || check.getUTCMonth() !== mo || check.getUTCDate() !== d) { throw new Error('"' + ymd + '" is not a date on the calendar.'); } var next = new Date(Date.UTC(y, mo, d + 1)); var start = ltapiDayStart_(ymd, tz); var end = ltapiDayStart_(next.toISOString().slice(0, 10), tz); return { from: new Date(start).toISOString().replace('.000Z', 'Z'), // The last microsecond of the day, so a start at 23:59:59.9995 still falls inside it. to: new Date(end - 1).toISOString().replace(/Z$/, '999Z'), label: ymd }; } // The first minute, as a UTC instant in milliseconds, whose local date in tz is ymd. Local // time zones sit between 12 hours behind and 14 hours ahead of UTC, so the answer lies within // 15 hours of UTC midnight. A binary search over minutes finds it in 11 steps, and it is right // on days when the clocks change at midnight, when local midnight does not exist. function ltapiDayStart_(ymd, tz) { var p = ymd.split('-'); var utcMidnight = Date.UTC(Number(p[0]), Number(p[1]) - 1, Number(p[2])); var lo = (utcMidnight - 15 * 3600000) / 60000; var hi = (utcMidnight + 15 * 3600000) / 60000; while (lo < hi) { var mid = Math.floor((lo + hi) / 2); if (Utilities.formatDate(new Date(mid * 60000), tz, 'yyyy-MM-dd') >= ymd) { hi = mid; } else { lo = mid + 1; } } return lo * 60000; } function ltapiTimeZone_() { try { var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(); if (tz) return tz; } catch (e) { // No spreadsheet to ask, for example when run from the editor. UTC is used instead. } return 'Etc/UTC'; } // Fetching and caching. // One list endpoint, read through the cache. Up to maxPages pages of LTAPI_PAGE_SIZE rows are // fetched. The result is {rows, more, error}. more says the API had rows past the last page. // error is the message of a later page that failed, when one did. function ltapiList_(path, query, seconds, toRow, maxPages) { var started = Date.now(); var pages = maxPages || LTAPI_MAX_PAGES; // The key is read once, so every page goes out on the same key the cache entry names. var key = ltapiKey_(); var cacheKey = ltapiCacheKey_(key, path, query); var cached = ltapiCacheGet_(cacheKey); if (cached) return cached; // One cell fetches at a time, so cells with the same arguments share one request and the // minute count stays exact. A cell that cannot get the lock in time asks for nothing. var lock = LockService.getScriptLock(); if (!lock.tryLock(LTAPI_LOCK_WAIT)) { throw new Error('Other cells are still loading Live Tennis API data. Tick the refresh box or edit the cell in a moment.'); } try { cached = ltapiCacheGet_(cacheKey); if (cached) return cached; var rows = []; var seen = {}; var more = false; var error = ''; var cut = false; var q = {}; Object.keys(query).forEach(function (k) { q[k] = query[k]; }); if (q.limit === undefined) q.limit = LTAPI_PAGE_SIZE; // Each later page starts a little before the previous one ended. Rows seen twice are // dropped by id, and a row that moved up while the pages were read is not missed. var step = q.limit > LTAPI_PAGE_OVERLAP * 2 ? q.limit - LTAPI_PAGE_OVERLAP : q.limit; for (var page = 0; page < pages; page++) { if (page > 0 && Date.now() - started > LTAPI_TIME_BUDGET) { more = true; cut = true; break; } q.offset = page * step; var body; try { body = ltapiFetch_(path, q, true, key); if (!body || !Array.isArray(body.data)) { throw new Error('Live Tennis API sent an answer this script cannot read. Try again later.'); } } catch (e) { if (page === 0) throw e; error = e.message; break; } var before = rows.length; body.data.forEach(function (record) { var id = record && record.id; if (id !== undefined && id !== null) { if (seen[id]) return; seen[id] = true; } rows.push(toRow(record)); }); more = !!(body.meta && body.meta.has_more); var total = body.meta && typeof body.meta.total === 'number' ? body.meta.total : null; if (page > 0 && body.data.length > 0 && rows.length === before) { // The page held only rows already seen, so the list moved. It is shown as cut short. more = true; cut = true; break; } if (!more && total !== null && rows.length < total) { // Fewer rows than the API counted. The list moved while it was read. more = true; cut = true; break; } if (!more || body.data.length === 0) break; } var result = { rows: rows, more: more, error: error }; // A list cut short by an error or by time is kept for a minute only. ltapiCachePut_(cacheKey, result, error || cut ? 60 : seconds); return result; } finally { lock.releaseLock(); } } // One GET request. Returns the parsed JSON body or throws an Error with a plain message. // counted is false only for GET /usage, which the API does not count. key is the saved key // unless the caller passes one. function ltapiFetch_(path, query, counted, key) { key = key || ltapiKey_(); var hash = ltapiHash_(key); if (counted) { // After a 429 the script waits out the time the API named before it asks again. var wait = ltapiWaitRead_(hash); if (wait) throw new Error(ltapiWaitMessage_(wait.kind, wait.until)); ltapiSpend_(hash); } var url = LTAPI_BASE_URL + path + ltapiQuery_(query); var response; try { response = UrlFetchApp.fetch(url, { method: 'get', headers: { 'X-API-Key': key, 'Accept': 'application/json' }, muteHttpExceptions: true, // A redirect would carry the key header to another address, so it is not followed. followRedirects: false }); } catch (e) { throw new Error('Could not reach Live Tennis API. Check your connection and try again in a minute.'); } var status = response.getResponseCode(); var body = null; try { body = JSON.parse(response.getContentText()); } catch (e) { body = null; } if (status === 200) return body; var code = body && body.error ? String(body.error) : ''; if (status === 401) { throw new Error('Live Tennis API did not accept the key. Open the Live Tennis API menu, choose Set API key and paste it again.'); } if (status === 403 && code === 'email_unverified') { throw new Error('This free key works once its email address is confirmed. Open the link Live Tennis API emailed you, then try again.'); } if (status === 403) { throw new Error('Your plan does not include this data. See https://livetennisapi.com/pricing'); } if (status === 429) { var now = Date.now(); var kind; var until; if (code === 'abuse_throttled' || code === 'client_blocked' || body && typeof body.retry_at_epoch === 'number') { kind = 'throttled'; until = body && typeof body.retry_at_epoch === 'number' ? body.retry_at_epoch * 1000 : now + 86400000; } else if (body && body.scope === 'day') { kind = 'day'; var resets = body.resets_at ? Date.parse(body.resets_at) : NaN; until = isNaN(resets) ? now + 3600000 : resets; } else { kind = 'minute'; var seconds = Number(ltapiHeader_(response, 'Retry-After')); until = now + (seconds > 0 ? seconds : 60) * 1000; } ltapiWaitWrite_(hash, kind, until); throw new Error(ltapiWaitMessage_(kind, until)); } if (status === 400) { var detail = body && body.detail ? ' ' + body.detail : ''; throw new Error('Live Tennis API refused the request (' + (code || 'bad request') + ').' + detail); } if (status >= 500) { throw new Error('Live Tennis API had a problem on its side (HTTP ' + status + '). Try again in a few minutes.'); } throw new Error('Live Tennis API answered HTTP ' + status + (code ? ' (' + code + ')' : '') + '.'); } function ltapiWaitMessage_(kind, until) { var when = ltapiWhen_(until); if (kind === 'day') { return 'The API key has used its requests for today. They reset at ' + when + '.'; } if (kind === 'throttled') { return 'The API has paused this key after too many requests. It can call again at ' + when + '.'; } return 'Too many requests this minute. Try again after ' + when + '.'; } // The wait after a 429 is kept in Script Properties, because a pause can last a day and the // cache keeps nothing longer than six hours. It belongs to the key that was refused. A // shorter wait never replaces a longer one that is still running. function ltapiWaitWrite_(hash, kind, until) { var current = ltapiWaitRead_(hash); if (current && current.until >= until) return; var text = JSON.stringify({ k: hash, kind: kind, until: until }); try { PropertiesService.getScriptProperties().setProperty(LTAPI_BLOCK_PROPERTY, text); CacheService.getScriptCache().remove('ltapi:wait'); } catch (e) { var seconds = Math.min(21600, Math.max(1, Math.ceil((until - Date.now()) / 1000))); CacheService.getScriptCache().put('ltapi:wait', text, seconds); } } // The longest wait still running for this key, from Script Properties or the cache. function ltapiWaitRead_(hash) { var raws = []; try { raws.push(PropertiesService.getScriptProperties().getProperty(LTAPI_BLOCK_PROPERTY)); } catch (e) { // Read the cache copy alone. } raws.push(CacheService.getScriptCache().get('ltapi:wait')); var best = null; for (var i = 0; i < raws.length; i++) { if (!raws[i]) continue; try { var w = JSON.parse(raws[i]); if (w && w.k === hash && typeof w.until === 'number' && w.until > Date.now() && (!best || w.until > best.until)) { best = w; } } catch (e) { // A damaged entry is ignored. } } return best; } function ltapiWaitClear_(hash, kind) { var w = ltapiWaitRead_(hash); if (!w || w.kind !== kind) return; try { PropertiesService.getScriptProperties().deleteProperty(LTAPI_BLOCK_PROPERTY); } catch (e) { // Nothing to clear there. } CacheService.getScriptCache().remove('ltapi:wait'); } function ltapiWhen_(ms) { var tz = ltapiTimeZone_(); return Utilities.formatDate(new Date(ms), tz, 'd MMM HH:mm') + ' (' + tz + ')'; } function ltapiHeader_(response, name) { var headers = response.getHeaders ? response.getHeaders() : {}; var want = name.toLowerCase(); for (var k in headers) { if (Object.prototype.hasOwnProperty.call(headers, k) && k.toLowerCase() === want) { return headers[k]; } } return null; } function ltapiQuery_(query) { var parts = Object.keys(query).sort().map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(query[k]); }); return parts.length ? '?' + parts.join('&') : ''; } function ltapiKey_() { var key = PropertiesService.getScriptProperties().getProperty(LTAPI_KEY_PROPERTY); if (!key) { throw new Error('No API key yet. Reload the spreadsheet, open the Live Tennis API menu and choose Set API key.'); } return key; } // A short fingerprint of the key, so a new key never reads answers cached for the old one. function ltapiHash_(key) { var bytes = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, key, Utilities.Charset.UTF_8); var hex = ''; for (var i = 0; i < 8; i++) { var b = (bytes[i] + 256) % 256; hex += (b < 16 ? '0' : '') + b.toString(16); } return hex; } function ltapiCacheKey_(key, path, query) { var raw = 'ltapi:' + LTAPI_VERSION + ':' + ltapiHash_(key) + ':' + path + ltapiQuery_(query); if (raw.length <= 200) return raw; return 'ltapi:' + LTAPI_VERSION + ':' + ltapiHash_(raw); } // CacheService keeps at most 100 KB under one key, so a long answer is split across keys. // Every character past ASCII is written as a \u escape first, so a split never falls inside // a character. function ltapiCachePut_(cacheKey, value, seconds) { var text = JSON.stringify(value).replace(/[\u007f-￿]/g, function (c) { return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); }); var parts = {}; var count = Math.max(1, Math.ceil(text.length / LTAPI_CHUNK)); for (var i = 0; i < count; i++) { parts[cacheKey + ':' + i] = text.slice(i * LTAPI_CHUNK, (i + 1) * LTAPI_CHUNK); } parts[cacheKey] = String(count); try { CacheService.getScriptCache().putAll(parts, Math.min(21600, seconds)); } catch (e) { // A failed cache write costs a request next time, never the answer. } } function ltapiCacheGet_(cacheKey) { var cache = CacheService.getScriptCache(); var count = Number(cache.get(cacheKey)); if (!count) return null; var names = []; for (var i = 0; i < count; i++) names.push(cacheKey + ':' + i); var got = cache.getAll(names); var text = ''; for (var j = 0; j < names.length; j++) { if (typeof got[names[j]] !== 'string') return null; text += got[names[j]]; } try { return JSON.parse(text); } catch (e) { return null; } } // The minute check. The script remembers when it sent each request in the last minute and // stops at the plan's per-minute limit, so a sheet that recalculates many cells at once // does not run the key into a 429. The API counts the day itself, and its 429 says when the // day resets. A limit larger than the log can hold is left to the API. function ltapiLimits_(hash) { var raw = PropertiesService.getScriptProperties().getProperty(LTAPI_LIMITS_PROPERTY); if (raw) { try { var saved = JSON.parse(raw); // Limits saved for another key do not apply to this one. if (saved && saved.k === hash) return { perMinute: saved.perMinute, perDay: saved.perDay }; } catch (e) { // Fall through to the free plan's limits. } } return { perMinute: LTAPI_FREE_LIMITS.perMinute, perDay: LTAPI_FREE_LIMITS.perDay }; } function ltapiSpend_(hash) { var limits = ltapiLimits_(hash); var now = Date.now(); var log = ltapiLogRead_(hash).filter(function (t) { return t > now - 60000; }); if (typeof limits.perMinute === 'number' && limits.perMinute <= LTAPI_LOG_MAX && log.length >= limits.perMinute) { throw new Error('This spreadsheet has sent ' + limits.perMinute + ' requests in the last minute, the limit of the plan. Try again in a minute.'); } log.push(now); ltapiLogWrite_(hash, log.slice(-LTAPI_LOG_MAX)); } function ltapiLogRead_(hash) { var raws = []; try { raws.push(PropertiesService.getScriptProperties().getProperty(LTAPI_LOG_PROPERTY)); } catch (e) { // Read the cache copy alone. } // The cache holds the log when properties cannot be written. Both are read, and the one // written last wins, so a stale copy in properties cannot hide newer requests. raws.push(CacheService.getScriptCache().get('ltapi:log')); var best = []; raws.forEach(function (raw) { if (!raw) return; try { var log = JSON.parse(raw); if (!log || log.k !== hash || !Array.isArray(log.t)) return; var times = log.t.filter(function (t) { return typeof t === 'number'; }); var last = times.length ? times[times.length - 1] : -1; var bestLast = best.length ? best[best.length - 1] : -1; if (last > bestLast || last === bestLast && times.length > best.length) best = times; } catch (e) { // A damaged log counts as empty. } }); return best; } function ltapiLogWrite_(hash, times) { var text = JSON.stringify({ k: hash, t: times }); try { PropertiesService.getScriptProperties().setProperty(LTAPI_LOG_PROPERTY, text); } catch (e) { // If properties cannot be written here, the cache holds the log instead. CacheService.getScriptCache().put('ltapi:log', text, 120); } }