UNPKG

@azteam/google-api

Version:

N/A

432 lines (383 loc) 14.2 kB
import GoogleOAuth2API from './GoogleOAuth2API'; import {DRIVE_SCOPE} from './scope'; // const UPLOAD_ENDPOINT = 'https://www.googleapis.com/upload'; // const UPLOAD_DRIVE_V3_ENDPOINT = `${UPLOAD_ENDPOINT}/drive/v3/files`; const DRIVE_V3_ENDPOINT = 'https://www.googleapis.com/drive/v3', DRIVE_V2_ENDPOINT = 'https://www.googleapis.com/drive/v2', TEAM_DRIVE_V3_ENDPOINT = `${DRIVE_V3_ENDPOINT}/drives`; export const DRIVE_FILE_TYPE = { FOLDER: 'application/vnd.google-apps.folder', FILE: 'application/vnd.google-apps.file', SHEET: 'application/vnd.google-apps.spreadsheet', }; class GoogleDriveAPI extends GoogleOAuth2API { constructor(accountType, credential, options = {}) { super( accountType, { ...credential, scope: DRIVE_SCOPE, }, options ); } getAuthLink(redirectURI, state, arrayScope = [DRIVE_SCOPE]) { return super.getAuthLink(redirectURI, state, arrayScope); } async hasScope(arrayScope = [DRIVE_SCOPE]) { return super.hasScope(arrayScope); } async _getAllItem(metadata) { const client = await this._getAuthClient(); let data = [], pageToken = null; do { const res = await client.get(`${DRIVE_V3_ENDPOINT}/files`, { pageToken, pageSize: 1000, supportsAllDrives: true, includeTeamDriveItems: true, ...metadata, }); pageToken = res.nextPageToken; if (res.files && res.files.length > 0) { data = [...data, ...res.files]; } else { pageToken = undefined; } } while (pageToken); return data; } async getFileInfo(driveId) { const client = await this._getAuthClient(); return client.get(`${DRIVE_V2_ENDPOINT}/files/${driveId}?supportsAllDrives=true`); } async checkFileLive(driveId) { const res = await this.getFileInfo(driveId); return !res.error; } async getAllFolder(containsName = null, parentId = 'root') { let query = `mimeType='${DRIVE_FILE_TYPE.FOLDER}' and trashed=false and '${parentId}' in parents`; if (containsName) { query = `name contains '${containsName}' and ${query}`; } return this._getAllItem({ q: query, }); } async getFolderByName(name, parentId = 'root') { const query = `name='${name}' and mimeType='${DRIVE_FILE_TYPE.FOLDER}' and trashed=false and '${parentId}' in parents`, res = await this._getAllItem({ q: query, }); if (res.length > 0) { return res[0]; } return null; } async getAllFile(containsName = null, parentId = 'root') { let query = `mimeType!='${DRIVE_FILE_TYPE.FOLDER}' and trashed=false and '${parentId}' in parents`; if (containsName) { query = `name contains '${containsName}' and ${query}`; } return this._getAllItem({ q: query, }); } async getFileByName(name, parentId = 'root') { const query = `name='${name}' and mimeType!='${DRIVE_FILE_TYPE.FOLDER}' and trashed=false and '${parentId}' in parents`, res = await this._getAllItem({ q: query, }); if (res.length > 0) { return res[0]; } return null; } async createFolder(name, parentId = null) { const client = await this._getAuthClient(), metadata = { name, mimeType: DRIVE_FILE_TYPE.FOLDER, }; if (parentId) { metadata.parents = [parentId]; } return client.post(`${DRIVE_V3_ENDPOINT}/files?supportsAllDrives=true`, metadata, false); } async getAllTeamDrive(containsName = null, notContainsName = null) { const client = await this._getAuthClient(), data = []; let query = null; if (containsName) { query = `name contains '${containsName}'`; } if (notContainsName) { if (containsName) { query += ' and '; } query += `not name contains '${notContainsName}'`; } let pageToken = null; do { const res = await client.get(TEAM_DRIVE_V3_ENDPOINT, { pageSize: 100, pageToken, q: query, }); pageToken = res.nextPageToken; if (res.drives && res.drives.length > 0) { data.push(...res.drives); } else { pageToken = undefined; } } while (pageToken); return data; } async getTeamDriveByName(name) { const client = await this._getAuthClient(), res = await client.get(TEAM_DRIVE_V3_ENDPOINT, { q: `name='${name}'`, }); if (res.drives.length > 0) { return res.drives[0]; } return null; } async cloneFile(driveId, name, parentId = null) { const client = await this._getAuthClient(), data = { name, }; if (parentId) { data.parents = [parentId]; } return client.post(`${DRIVE_V3_ENDPOINT}/files/${driveId}/copy?supportsAllDrives=true`, data, false); } async moveItem(driveId, toParentId, moveParentId = null) { const client = await this._getAuthClient(); let moveParent = ''; if (moveParentId) { moveParent = `&removeParents=${moveParentId}`; } const res = await client.patch( `${DRIVE_V3_ENDPOINT}/files/${driveId}?supportsAllDrives=true&addParents=${toParentId}${moveParent}`, {}, false ); return res.id === driveId; } async rename(driveId, newName) { const client = await this._getAuthClient(), res = await client.patch( `${DRIVE_V3_ENDPOINT}/files/${driveId}?supportsAllDrives=true`, { name: newName, }, false ); return res.id === driveId; } async deleteItem(driveId) { const client = await this._getAuthClient(), res = await client.delete(`${DRIVE_V3_ENDPOINT}/files/${driveId}?supportsAllDrives=true`, {}, false); return !res.error; } async findFileInTrash(name) { return this._getAllItem({ q: `name ='${name}' and trashed = true`, }); } async findFileAllTeamDrive(name) { return this._getAllItem({ q: `name ='${name}' and trashed = false`, }); } async unTrashItem(driveId) { const client = await this._getAuthClient(), res = await client.post(`${DRIVE_V2_ENDPOINT}/files/${driveId}/untrash?supportsAllDrives=true`, {}, false); return !res.error; } async hideTeamDrive(driveId) { const client = await this._getAuthClient(), res = await client.post(`${TEAM_DRIVE_V3_ENDPOINT}/${driveId}/hide`); return res.id === driveId; } async showTeamDrive(driveId) { const client = await this._getAuthClient(), res = await client.post(`${TEAM_DRIVE_V3_ENDPOINT}/${driveId}/unhide`); return res.id === driveId; } async changeNameTeamDrive(driveId, name) { const client = await this._getAuthClient(), res = await client.patch( `${TEAM_DRIVE_V3_ENDPOINT}/${driveId}`, { name, }, false ); return res.id === driveId && res.name === name; } async createTeamDrive(name, uuid = null) { const client = await this._getAuthClient(), res = await client.post( `${TEAM_DRIVE_V3_ENDPOINT}?requestId=${uuid || Date.now()}`, { name, }, false ); if (res.id) { return res.id; } return null; } async deleteTeamDrive(teamDriveId) { const client = await this._getAuthClient(), res = await client.delete(`${DRIVE_V3_ENDPOINT}/drives/${teamDriveId}`, {}, false); return !res.error; } async addUserToTeamDrive(driveId, email, role) { const client = await this._getAuthClient(); return client.post( `${DRIVE_V3_ENDPOINT}/files/${driveId}/permissions?supportsAllDrives=true`, { role, type: 'user', emailAddress: email, }, false ); } async addOrganizerToTeamDrive(driveId, email) { return this.addUserToTeamDrive(driveId, email, 'organizer'); } async addFileOrganizerToTeamDrive(driveId, email) { return this.addUserToTeamDrive(driveId, email, 'fileOrganizer'); } async addReaderToTeamDrive(driveId, email) { return this.addUserToTeamDrive(driveId, email, 'reader'); } // async moveFileToFolder(file_id, folder_id) { // const client = await this._getAuthClient(); // const json = await client.patchQueryUrl(`${DRIVE_V3_ENDPOINT}/${file_id}`, { // addParents: folder_id, // supportsAllDrives: true, // supportsTeamDrives: true, // alt: 'json' // }); // return json; // } // // async upload(file, options = {}) { // // if (fs.existsSync(file)) { // options.file_size = fs.statSync(file).size; // options.mime_type = mime.contentType(path.extname(file)); // options.name = options.name ? options.name : path.basename(file); // // if (options.file_size >= 4000000) { // return this._resumableUpload(file, options); // } else { // return this._multipartUpload(file, options); // } // } // // throw new ErrorException('GOOGLE_DRIVE_UPLOAD', `File not ${file} exists`); // } // // async _multipartUpload(file, options = {}) { // // const metadata = { // name: options.name, // mimeType: options.mime_type // }; // if (options.parent) { // metadata.parents = [options.parent]; // } // // const data = [ // { // 'Content-Disposition': 'application/json; charset=UTF-8', // body: JSON.stringify(metadata) // }, // { // 'content-type': options.mime_type, // body: fs.createReadStream(file) // } // ]; // const client = await this._getAuthClient(); // return await client.postMultipart(UPLOAD_DRIVE_V3_ENDPOINT + '?uploadType=multipart', data); // } // // async _resumableUpload(file, options = {}) { // const metadata = { // name: options.name, // mimeType: options.mime_type // }; // if (options.parent) { // metadata.parents = [options.parent]; // } // const client = await this._getAuthClient(); // let res = await client.noFollow() // .responseFull() // .addHeader('Content-Type', 'application/json; charset=UTF-8') // .addHeader('X-Upload-Content-Type', options.mime_type) // .addHeader('X-Upload-Content-Length', options.file_size) // .postJSON(UPLOAD_DRIVE_V3_ENDPOINT + '?uploadType=resumable', metadata); // // if (res.headers.location) { // const resumable_url = res.headers.location; // const chunk_size = 4 * 1024 * 1024; // let start = 0; // // while (start < options.file_size) { // const chunk = readChunk.sync(file, start, chunk_size); // const end = start + chunk.length - 1; // const range = `bytes ${start}-${end}/${options.file_size}`; // start = end + 1; // // let retry = 0; // let res = null; // do { // res = await client.responseFull() // .addHeader('Content-Length', chunk.length) // .addHeader('Content-Range', range) // .putRaw(resumable_url, chunk); // if (res.headers.range) { // retry = 100; // const current_upload = Number(res.headers.range.replace('bytes=0-', '')); // const process = 100 * current_upload / options.file_size; // // console.log('Uploading: ', `${process.toFixed(2)}%`); // } else if (res.statusCode === 200) { // retry = 100; // } else { // console.log(`Error ${res.statusCode}: wait retry ${retry}`); // await timeout(1000); // retry++; // // } // } while (retry < 5); // if (retry !== 100) { // console.error('error upload drive', res.statusCode, range, res.headers); // } // } // // const data = await client.responseFull() // .addHeader('Content-Length', 0) // .addHeader('Content-Range', `bytes */${options.file_size}`) // .put(resumable_url); // // if (data.body) { // return JSON.parse(data.body); // } // console.error('file size', options.file_size); // console.error('error success drive', data.statusCode, data.headers); // return false; // } // return false; // } } export default GoogleDriveAPI;