| 1 | // Google tokens exist only in this page's memory. The exported File is the only |
| 2 | // thing passed to the app, through its ordinary multipart upload form. |
| 3 | export const MAX_BYTES = 10 * 1024 * 1024 |
| 4 | const SCOPE = 'https://www.googleapis.com/auth/drive.file' |
| 5 | const TYPES = { |
| 6 | docs: ['application/vnd.google-apps.document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.docx'], |
| 7 | sheets: ['application/vnd.google-apps.spreadsheet', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx'], |
| 8 | } |
| 9 | let libraries |
| 10 | |
| 11 | function script(src) { |
| 12 | return new Promise((resolve, reject) => { |
| 13 | const tag = document.createElement('script') |
| 14 | const timer = setTimeout(() => { tag.remove(); reject(new Error('failed')) }, 15000) |
| 15 | tag.src = src |
| 16 | tag.onload = () => { clearTimeout(timer); resolve() } |
| 17 | tag.onerror = () => { clearTimeout(timer); tag.remove(); reject(new Error('failed')) } |
| 18 | document.head.append(tag) |
| 19 | }) |
| 20 | } |
| 21 | |
| 22 | function load() { |
| 23 | if (!libraries) libraries = Promise.all([ |
| 24 | globalThis.google?.accounts?.oauth2 ? null : script('https://accounts.google.com/gsi/client'), |
| 25 | globalThis.gapi ? null : script('https://apis.google.com/js/api.js'), |
| 26 | ]).then(() => new Promise((resolve, reject) => { |
| 27 | gapi.load('picker', { callback: resolve, onerror: () => reject(new Error('failed')), |
| 28 | timeout: 15000, ontimeout: () => reject(new Error('failed')) }) |
| 29 | })).catch(error => { libraries = null; throw error }) |
| 30 | return libraries |
| 31 | } |
| 32 | |
| 33 | export function selection(kind, item) { |
| 34 | const type = TYPES[kind] |
| 35 | if (!type || !item || item.mimeType !== type[0] || typeof item.id !== 'string' || !/^[a-zA-Z0-9_-]{1,256}$/.test(item.id)) throw new Error('unavailable') |
| 36 | const name = String(item.name || 'Import').replace(/[\\/\u0000-\u001f\u007f]/g, '_').slice(0, 200) |
| 37 | return { url: 'https://www.googleapis.com/drive/v3/files/' + item.id + '/export?mimeType=' + encodeURIComponent(type[1]), |
| 38 | name: name + type[2], mime: type[1] } |
| 39 | } |
| 40 | |
| 41 | export async function download(kind, item, token, signal, fetcher = fetch) { |
| 42 | const selected = selection(kind, item) |
| 43 | const response = await fetcher(selected.url, { headers: { Authorization: 'Bearer ' + token }, |
| 44 | credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer', signal }) |
| 45 | if (!response.ok) { |
| 46 | // Only inspect a bounded Google error code; never surface Google's raw text. |
| 47 | let reason = '' |
| 48 | if (response.body) { |
| 49 | const reader = response.body.getReader() |
| 50 | try { |
| 51 | let size = 0, body = '', decoder = new TextDecoder() |
| 52 | for (;;) { |
| 53 | const { done, value } = await reader.read() |
| 54 | if (done) break |
| 55 | size += value.byteLength |
| 56 | if (size > 16384) break |
| 57 | body += decoder.decode(value, { stream: true }) |
| 58 | } |
| 59 | if (size <= 16384) { |
| 60 | try { reason = JSON.parse(body + decoder.decode()).error?.errors?.[0]?.reason || '' } catch {} |
| 61 | } |
| 62 | } finally { await reader.cancel() } |
| 63 | } |
| 64 | if (reason === 'exportSizeLimitExceeded' || response.status === 413) throw new Error('tooLarge') |
| 65 | throw new Error(response.status === 401 || response.status === 403 ? 'denied' : 'unavailable') |
| 66 | } |
| 67 | const declared = Number(response.headers.get('Content-Length')) |
| 68 | if (declared > MAX_BYTES) { await response.body?.cancel(); throw new Error('tooLarge') } |
| 69 | if (!response.body) throw new Error('failed') |
| 70 | const reader = response.body.getReader() |
| 71 | const chunks = [] |
| 72 | let size = 0 |
| 73 | try { |
| 74 | for (;;) { |
| 75 | const { done, value } = await reader.read() |
| 76 | if (done) break |
| 77 | size += value.byteLength |
| 78 | if (size > MAX_BYTES) throw new Error('tooLarge') |
| 79 | chunks.push(value) |
| 80 | } |
| 81 | } finally { await reader.cancel() } |
| 82 | if (!size) throw new Error('failed') |
| 83 | return new File(chunks, selected.name, { type: selected.mime }) |
| 84 | } |
| 85 | |
| 86 | export function mount(root) { |
| 87 | const data = root.dataset |
| 88 | const labels = JSON.parse(data.googleLabels) |
| 89 | const choose = root.querySelector('[data-google-choose]') |
| 90 | const cancel = root.querySelector('[data-google-cancel]') |
| 91 | const chooseWrap = root.querySelector('[data-google-choose-wrap]') |
| 92 | const cancelWrap = root.querySelector('[data-google-cancel-wrap]') |
| 93 | const status = root.querySelector('[data-google-status]') |
| 94 | const form = document.getElementById(data.googleForm) |
| 95 | const input = document.getElementById(data.googleInput) |
| 96 | if (!TYPES[data.googleKind] || !form || input?.form !== form || input.type !== 'file' || |
| 97 | form.method.toLowerCase() !== 'post' || new URL(form.action).origin !== location.origin) return |
| 98 | let ready = false, active = false, generation = 0, picker = null, controller = null, timeout = null |
| 99 | const say = key => { status.textContent = labels[key] || labels.failed } |
| 100 | const reset = key => { |
| 101 | generation++ |
| 102 | active = false |
| 103 | clearTimeout(timeout) |
| 104 | controller?.abort(); controller = null |
| 105 | picker?.dispose(); picker = null |
| 106 | choose.disabled = false |
| 107 | cancelWrap.hidden = true |
| 108 | root.removeAttribute('aria-busy') |
| 109 | if (key) say(key) |
| 110 | } |
| 111 | const initialize = async () => { |
| 112 | chooseWrap.hidden = false; choose.disabled = true; say('loading') |
| 113 | try { await load(); ready = true; say('ready') } catch { say('failed') } |
| 114 | choose.disabled = false |
| 115 | } |
| 116 | choose.addEventListener('click', () => { |
| 117 | if (active || document.prerendering) return |
| 118 | if (!ready) { initialize(); return } // Next click retains the popup's user gesture. |
| 119 | active = true |
| 120 | const attempt = ++generation |
| 121 | choose.disabled = true; cancelWrap.hidden = false; root.setAttribute('aria-busy', 'true'); say('connecting') |
| 122 | timeout = setTimeout(() => { if (attempt === generation) reset('failed') }, 120000) |
| 123 | try { |
| 124 | const client = google.accounts.oauth2.initTokenClient({ client_id: data.googleClient, scope: SCOPE, |
| 125 | include_granted_scopes: false, |
| 126 | error_callback: error => { if (attempt === generation) reset(error.type === 'popup_closed' ? 'cancelled' : 'failed') }, |
| 127 | callback: response => { |
| 128 | if (attempt !== generation) return |
| 129 | if (response.error || !response.access_token || !google.accounts.oauth2.hasGrantedAllScopes(response, SCOPE)) { reset('denied'); return } |
| 130 | let token = response.access_token |
| 131 | let picked = false |
| 132 | clearTimeout(timeout) |
| 133 | try { |
| 134 | picker = new google.picker.PickerBuilder().setDeveloperKey(data.googleKey).setAppId(data.googleApp) |
| 135 | .setOAuthToken(token).setOrigin(location.origin) |
| 136 | .addView(new google.picker.DocsView().setMimeTypes(TYPES[data.googleKind][0])) |
| 137 | .setCallback(async result => { |
| 138 | if (attempt !== generation) { token = ''; return } |
| 139 | if (result.action === google.picker.Action.CANCEL && !picked) { token = ''; reset('cancelled'); choose.focus(); return } |
| 140 | if (result.action !== google.picker.Action.PICKED || picked) return |
| 141 | picked = true |
| 142 | picker?.dispose(); picker = null |
| 143 | controller = new AbortController() |
| 144 | const signal = controller.signal |
| 145 | timeout = setTimeout(() => controller?.abort(), 60000) |
| 146 | say('exporting') |
| 147 | try { |
| 148 | const file = await download(data.googleKind, result.docs?.[0], token, signal) |
| 149 | token = '' |
| 150 | if (attempt !== generation) return |
| 151 | clearTimeout(timeout) |
| 152 | const transfer = new DataTransfer() |
| 153 | transfer.items.add(file); input.files = transfer.files |
| 154 | if (!form.checkValidity()) { reset('ready'); form.reportValidity(); return } |
| 155 | form.requestSubmit() |
| 156 | } catch (error) { |
| 157 | token = '' |
| 158 | if (attempt === generation) reset(error.message in labels ? error.message : 'failed') |
| 159 | } |
| 160 | }).build() |
| 161 | picker.setVisible(true) |
| 162 | } catch { token = ''; reset('failed') } |
| 163 | }, |
| 164 | }) |
| 165 | client.requestAccessToken({ prompt: 'select_account' }) |
| 166 | } catch { reset('failed') } |
| 167 | }) |
| 168 | cancel.addEventListener('click', () => { reset('cancelled'); choose.focus() }) |
| 169 | form.addEventListener('submit', () => { reset(); choose.disabled = true }) |
| 170 | addEventListener('pagehide', () => reset()) |
| 171 | addEventListener('pageshow', event => { if (event.persisted) { input.value = ''; reset('ready') } }) |
| 172 | if (document.prerendering) document.addEventListener('prerenderingchange', initialize, { once: true }) |
| 173 | else initialize() |
| 174 | } |
| 175 | |
| 176 | if (typeof document !== 'undefined') { |
| 177 | for (const root of document.querySelectorAll('[estilo-google-import]')) mount(root) |
| 178 | } |
| 179 | |