All files / src/web google-drive.js

63.54% Statements 61/96
50% Branches 11/22
73.68% Functions 14/19
63.73% Lines 58/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174        2x 2x 2x 2x 2x 2x   2x 2x 2x   2x       6x 6x 6x       5x 4x 4x 4x     5x       4x 4x                                               4x 4x 4x 4x 4x 4x         1x 1x 1x 1x 1x 1x         1x       1x         1x       1x 1x 1x 1x 1x   1x                                           2x     2x 2x   2x   2x         2x                   2x 2x 2x 2x       2x 2x 2x 2x 2x 2x               2x                  
import { discFor } from "../fdc.js";
import { uint8ArrayToString } from "../binary.js";
import { debounce } from "../debounce.js";
 
const MIME_TYPE = "application/vnd.jsbeeb.disc-image";
const CLIENT_ID = "356883185894-bhim19837nroivv18p0j25gecora60r5.apps.googleusercontent.com";
const SCOPES = "https://www.googleapis.com/auth/drive.file";
const DISCOVERY_DOC = "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest";
const FILE_FIELDS = "id,name,capabilities";
const PARENT_FOLDER_NAME = "jsbeeb disc images";
 
const boundary = "-------314159265358979323846";
const delimiter = `\r\n--${boundary}\r\n`;
const close_delim = `\r\n--${boundary}--`;
 
const FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
 
export class GoogleDriveLoader {
    constructor() {
        this.authorized = false;
        this.parentFolderId = undefined;
        this.driveClient = undefined;
    }
 
    initialise() {
        if (!this._initialising) {
            this._initialising = this._initialise().catch((error) => {
                this._initialising = undefined;
                throw error;
            });
        }
        return this._initialising;
    }
 
    async _initialise() {
        console.log("Creating GAPI");
        await this._loadScript("https://apis.google.com/js/api.js");
        console.log("Got GAPI, creating token client");
        this.gapi = window.gapi;
        await this._loadScript("https://accounts.google.com/gsi/client");
        this.tokenClient = window.google.accounts.oauth2.initTokenClient({
            client_id: CLIENT_ID,
            scope: SCOPES,
            error_callback: "", // defined later
            callback: "", // defined later
        });
        console.log("Token client created, loading client");
 
        await this.gapi.load("client", async () => {
            console.log("Client loaded; initialising GAPI");
            await this.gapi.client.init({ discoveryDocs: [DISCOVERY_DOC] });
            console.log("GAPI initialised");
            this.driveClient = this.gapi.client.drive;
        });
        console.log("Google Drive: available");
        return true;
    }
 
    _loadScript(src) {
        // https://github.com/google/google-api-javascript-client/issues/319
        return new Promise((resolve, reject) => {
            const script = document.createElement("script");
            script.src = src;
            script.onload = resolve;
            script.onerror = () => reject(new Error(`Failed to fetch ${src}; a browser extension may be blocking it`));
            document.body.appendChild(script);
        });
    }
 
    authorize(imm) {
        Iif (this.authorized) return true;
        Iif (imm) return false;
        return new Promise((resolve, reject) => {
            console.log("Authorizing...");
            this.tokenClient.callback = (resp) => {
                Eif (resp.error !== undefined) return reject(new Error(resp.error_description ?? resp.error));
                console.log("Authorized OK");
                this.authorized = true;
                resolve(true);
            };
            this.tokenClient.error_callback = (resp) => {
                console.log(`Token client failure: ${resp.type}; failed to authorize`);
                reject(new Error(`Token client failure: ${resp.type}; failed to authorize`));
            };
            this.tokenClient.requestAccessToken({ select_account: false });
        });
    }
 
    async listFiles() {
        const query = {
            q: `mimeType = '${MIME_TYPE}' and trashed = false`,
            fields: `nextPageToken, files(${FILE_FIELDS})`,
        };
        let response = await this.driveClient.files.list(query);
        let result = response.result.files;
        while (response.result.nextPageToken) {
            response = await this.driveClient.files.list({ ...query, pageToken: response.result.nextPageToken });
            result = result.concat(response.result.files);
        }
        return result;
    }
 
    async _findOrCreateParentFolder() {
        const list = await this.driveClient.files.list({
            q: `name = '${PARENT_FOLDER_NAME}' and mimeType = '${FOLDER_MIME_TYPE}' and trashed = false`,
            corpora: "user",
        });
        if (list.result.files.length === 1) {
            console.log("Found existing parent folder");
            return list.result.files[0].id;
        }
        console.log(`Creating parent folder ${PARENT_FOLDER_NAME}`);
        const file = await this.driveClient.files.create({
            resource: { name: PARENT_FOLDER_NAME, mimeType: FOLDER_MIME_TYPE },
            fields: "id",
        });
        console.log("Folder Id:", file.result.id);
        return file.result.id;
    }
 
    async saveFile(name, data, idOrNone) {
        Iif (this.parentFolderId === undefined) {
            this.parentFolderId = await this._findOrCreateParentFolder();
        }
        const metadata = { name, mimeType: MIME_TYPE };
        Eif (!idOrNone) metadata.parents = [this.parentFolderId];
 
        const base64Data = btoa(uint8ArrayToString(data));
        const multipartRequestBody =
            `${delimiter}Content-Type: application/json\r\n\r\n` +
            `${JSON.stringify(metadata)}${delimiter}` +
            `Content-Type: ${MIME_TYPE}\r\nContent-Transfer-Encoding: base64\r\n\r\n` +
            `${base64Data}${close_delim}`;
 
        return this.gapi.client.request({
            path: `/upload/drive/v3/files${idOrNone ? `/${idOrNone}` : ""}`,
            method: idOrNone ? "PATCH" : "POST",
            params: { uploadType: "multipart", newRevision: false, fields: FILE_FIELDS },
            headers: { "Content-Type": `multipart/mixed; boundary="${boundary}"` },
            body: multipartRequestBody,
        });
    }
 
    async create(name, data, layout) {
        console.log(`Google Drive: creating disc image: '${name}'`);
        const response = await this.saveFile(name, data);
        const meta = response.result;
        return { fileId: meta.id, disc: this.makeDisc(data, meta, layout) };
    }
 
    makeDisc(data, meta, layout) {
        let flusher = null;
        const name = meta.name;
        const id = meta.id;
        if (meta.capabilities.canEdit) {
            console.log("Making editable disc");
            flusher = debounce(async (changedData) => {
                console.log("Data changed...");
                await this.saveFile(name, changedData, id);
                console.log("Saved ok");
            }, 200);
        } else E{
            console.log("Making read-only disc");
        }
        return discFor(name, data, flusher, layout);
    }
 
    async load(fileId, layout) {
        const meta = (await this.driveClient.files.get({ fileId, fields: FILE_FIELDS })).result;
        const data = (await this.driveClient.files.get({ fileId, alt: "media" })).body;
        return this.makeDisc(data, meta, layout);
    }
}