Files
khb_microservices/packages/accounting_automation/src/drive.ts

80 lines
3.6 KiB
TypeScript

import type { FetchFn, GoogleAuth } from "./google.js";
export interface DriveStore {
/** Путь папок внутри корневой папки; создаёт недостающие, возвращает id последней. */
ensureFolder(pathParts: string[]): Promise<string>;
upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }>;
/** Текст Google-документа (export text/plain). */
exportDocText(docId: string): Promise<string>;
}
export const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
const API = "https://www.googleapis.com/drive/v3";
const UPLOAD = "https://www.googleapis.com/upload/drive/v3/files";
/** Drive REST API v3, общие диски включены (supportsAllDrives). */
export class DriveClient implements DriveStore {
private folderCache = new Map<string, string>();
constructor(private o: { auth: GoogleAuth; rootFolderId: string; fetchFn?: FetchFn }) {}
private async call(url: string, init: RequestInit = {}): Promise<Response> {
const token = await this.o.auth.getAccessToken([DRIVE_SCOPE]);
const res = await (this.o.fetchFn ?? fetch)(url, { ...init, headers: { ...(init.headers ?? {}), authorization: `Bearer ${token}` } });
if (!res.ok) throw new Error(`Drive ${res.status}: ${(await res.text()).slice(0, 300)}`);
return res;
}
async ensureFolder(pathParts: string[]): Promise<string> {
let parent = this.o.rootFolderId;
for (const raw of pathParts) {
const name = raw.trim() || "_";
const ck = `${parent}/${name}`;
const cached = this.folderCache.get(ck);
if (cached) {
parent = cached;
continue;
}
const esc = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const q = `name='${esc}' and mimeType='application/vnd.google-apps.folder' and '${parent}' in parents and trashed=false`;
const params = new URLSearchParams({ q, fields: "files(id,name)", supportsAllDrives: "true", includeItemsFromAllDrives: "true", pageSize: "2" });
const found = (await (await this.call(`${API}/files?${params}`)).json()) as { files?: { id: string }[] };
let id = found.files?.[0]?.id;
if (!id) {
const created = (await (
await this.call(`${API}/files?supportsAllDrives=true&fields=id`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name, mimeType: "application/vnd.google-apps.folder", parents: [parent] }),
})
).json()) as { id: string };
id = created.id;
}
this.folderCache.set(ck, id);
parent = id;
}
return parent;
}
async upload(name: string, mime: string, bytes: Buffer, folderId: string): Promise<{ id: string }> {
const boundary = "khb" + Math.random().toString(36).slice(2);
const meta = JSON.stringify({ name, parents: [folderId] });
const body = Buffer.concat([
Buffer.from(`--${boundary}\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n--${boundary}\r\ncontent-type: ${mime}\r\n\r\n`),
bytes,
Buffer.from(`\r\n--${boundary}--`),
]);
const res = await this.call(`${UPLOAD}?uploadType=multipart&supportsAllDrives=true&fields=id`, {
method: "POST",
headers: { "content-type": `multipart/related; boundary=${boundary}` },
body,
});
const j = (await res.json()) as { id: string };
return { id: j.id };
}
async exportDocText(docId: string): Promise<string> {
const res = await this.call(`${API}/files/${encodeURIComponent(docId)}/export?mimeType=${encodeURIComponent("text/plain")}`);
return await res.text();
}
}