/* eslint-disable @typescript-eslint/camelcase */ // Due to import { drive_v3 } from "googleapis"; import fs from "fs"; import Directory from "./directory"; class File { protected drive: drive_v3.Drive; public id: string; constructor(drive: drive_v3.Drive, id: string) { this.drive = drive; this.id = id; } /** * 현재 파일/폴더의 상위 디렉토리를 표시합니다. * 최상단의 있을 경우, 루트 디렉토리가 반환됩니다. */ public async parentDirectory(): Promise { const folder = await this.drive.files.get( { fileId: this.id, fields: "parents" }); return (folder.data.parents && typeof folder.data.parents[0] === "string") ? new Directory(this.drive, folder.data.parents[0]) : new Directory(this.drive); } /** * 현재 파일의 이름을 반환합니다. */ public async getName(): Promise { const file = await this.getInfo("name"); return file.name as string; } /** * 현재 파일의 크기를 반환합니다. */ public async getSize(): Promise { const file = await this.getInfo("size"); return file.size as string; } /** * 현재 파일의 정보를 반환합니다 * * @param fields 받을 정보를 정합니다 ex.`name`, `size` */ public async getInfo(fields?: string): Promise { const file = await this.drive.files.get({ fileId: this.id, fields }); return file.data; } /** * 현재 파일을 로컬로 다운로드 합니다. * * @param fileName 다운로드할 위치 */ public async download(fileName: string): Promise { // For converting document formats, and for downloading template // documents, see the method drive.files.export(): // https://developers.google.com/drive/api/v3/manage-downloads return this.drive.files .get({fileId: this.id, alt: 'media'}, {responseType: 'stream'}) .then(res => { return new Promise((resolve) => { const dest = fs.createWriteStream(fileName); // eslint-disable-next-line @typescript-eslint/no-explicit-any (res.data as any).on('end', () => { resolve(); }).pipe(dest); }); }); } /** * 현재 파일/폴더를 지정한 디렉토리로 이동합니다 * * @param destinationDirectory 이동할 도착지 디렉토리 */ public async move(destinationDirectory: Directory): Promise { const file = await this.drive.files.get({ fileId: this.id, fields: 'parents' }); const parents = file.data.parents; if (parents === undefined || parents === null) return false; await this.drive.files.update({ fileId: this.id, addParents: destinationDirectory.id, removeParents: parents.join(','), fields: 'id, parents' }); return true; } /** * 파일/폴더를 삭제합니다. * * @returns 현재 파일/폴더의 상위 폴더를 반환합니다. */ public async delete(): Promise { const parent = await this.parentDirectory(); await this.drive.files.delete({ fileId: this.id }); return parent; } /** * 파일/폴더의 이름을 변경합니다. 변경후 file의 id 가 갱신되는 경우, 현 오브젝트에 갱신됩니다. * * @returns 성공여부를 반환합니다 (boolean) */ public async rename(fileName: string): Promise { const file = await this.drive.files.update({ fileId: this.id, requestBody: { name: fileName } }); if (typeof file.data.id === "undefined" || file.data.id === null) { return false; } this.id = file.data.id; return true; } } export default File;